imsd-messages/tests/Sync/main.cpp

921 lines
61 KiB
C++
Raw Permalink Normal View History

Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Sync over a fake transport that records every call and answers when the
// test says so; each case is a section below.
#include <signal.h>
#include <sys/resource.h>
import std;
import ImsdMessages;
using namespace ImsdMessages;
namespace fs = std::filesystem;
namespace {
std::int32_t failures = 0;
void Check(bool ok, std::string_view what) {
std::println("{} {}", ok ? "PASS" : "FAIL", what);
if (!ok) ++failures;
}
struct Fake : ImsdTransport {
struct SendCall {
std::string number;
std::string text;
bool statusReport;
std::function<void(SendResult)> done;
};
std::vector<Done> subscribes;
std::vector<std::function<void(StatusResult)>> statuses;
std::vector<std::function<void(ListResult)>> lists;
std::vector<std::pair<std::string, Done>> deletes;
std::vector<SendCall> sends;
void Subscribe(Done done) override { subscribes.push_back(std::move(done)); }
void GetStatus(std::function<void(StatusResult)> done) override { statuses.push_back(std::move(done)); }
void List(std::function<void(ListResult)> done) override { lists.push_back(std::move(done)); }
void Delete(std::string id, Done done) override { deletes.emplace_back(std::move(id), std::move(done)); }
void Send(std::string number, std::string text, bool statusReport, std::function<void(SendResult)> done) override {
sends.push_back({ std::move(number), std::move(text), statusReport, std::move(done) });
}
// Answer the oldest pending call of a kind; the callback is taken out
// first, because answering enqueues the next calls.
void AnswerSubscribe(std::optional<BusError> err = std::nullopt) {
Done d = std::move(subscribes.front());
subscribes.erase(subscribes.begin());
d(err);
}
void AnswerStatus(StatusResult r) {
std::function<void(StatusResult)> d = std::move(statuses.front());
statuses.erase(statuses.begin());
d(std::move(r));
}
void AnswerList(ListResult r) {
std::function<void(ListResult)> d = std::move(lists.front());
lists.erase(lists.begin());
d(std::move(r));
}
void AnswerDelete(std::optional<BusError> err = std::nullopt) {
Done d = std::move(deletes.front().second);
deletes.erase(deletes.begin());
d(err);
}
void AnswerSend(SendResult r) {
std::function<void(SendResult)> d = std::move(sends.front().done);
sends.erase(sends.begin());
d(std::move(r));
}
};
struct Recorder : SyncListener {
std::vector<AppStatus> statuses;
std::vector<Message> imported;
std::vector<Message> unstored;
std::vector<Message> changed;
std::vector<std::string> logs;
void OnStatus(const AppStatus& s) override { statuses.push_back(s); }
void OnImported(const Message& m) override { imported.push_back(m); }
void OnUnstored(const Message& m) override { unstored.push_back(m); }
void OnMessageChanged(const Message& m) override { changed.push_back(m); }
void OnLog(std::string_view line) override { logs.emplace_back(line); }
};
ReceivedMessage Text(std::string_view id, std::string_view from, std::string_view text, std::int64_t received) {
ReceivedMessage r;
r.imsdId = std::string(id);
r.from = std::string(from);
r.text = std::string(text);
r.timestamp = "2026-10-17T00:41:40+02:00";
r.received = received;
r.sc = "+31624000000";
return r;
}
// A registered subscriber whose service centre is abroad (an MVNO's).
Status Online() {
Status s;
s.enabled = true;
s.registered = true;
s.smsc = "+447785016005";
s.ownNumber = "+31612345678";
s.simOperator = "20408";
return s;
}
BusError Error(BusError::Kind kind, std::string_view message) {
return { kind, std::string(message) };
}
// Fills the store until it refuses a write, the file-size limit standing in
// for a full disk; the limit as it was comes back, to be set again.
rlimit FillUntilRefused(MessageStore& store, const fs::path& dir) {
signal(SIGXFSZ, SIG_IGN);
rlimit before{};
getrlimit(RLIMIT_FSIZE, &before);
rlim_t largest = 0;
for (const auto& entry : fs::directory_iterator(dir)) if (entry.is_regular_file()) largest = std::max(largest, static_cast<rlim_t>(entry.file_size()));
rlimit limit{};
limit.rlim_cur = largest;
limit.rlim_max = before.rlim_max;
setrlimit(RLIMIT_FSIZE, &limit);
Message filler;
filler.conversation = "+31621308050";
filler.peer = "+31621308050";
filler.direction = Direction::Outgoing;
filler.text = std::string(4096, 'x');
filler.state = MessageState::Sent;
filler.read = true;
for (std::size_t i = 0; i < 5000 && store.Add(filler); ++i) {}
return before;
}
}
int main() {
const fs::path dir = fs::temp_directory_path() / "imsd-messages-sync";
fs::remove_all(dir);
MessageStore store(dir);
store.Add(MessageFromReceived(Text("ims-sms-in-1-1", "+31621308050", "already here", 1000)));
Fake bus;
Recorder events;
Sync sync(store, bus, events);
// --- start: Subscribe, then GetStatus and List at once -------------------
Check(!sync.Current().imsdPresent && BannerText(sync.Current()) == "imsd is not running", "before imsd appears the banner says so");
sync.OnImsdAppeared();
Check(bus.subscribes.size() == 1 && bus.statuses.empty() && bus.lists.empty(), "Subscribe is called first, nothing else yet");
bus.AnswerSubscribe();
Check(sync.Current().subscribed && bus.statuses.size() == 1 && bus.lists.size() == 1, "after Subscribe: GetStatus and List at once — a listed text keys itself");
Check(BannerText(sync.Current()) == "Connecting to imsd\u2026" && !CanSend(sync.Current()), "until GetStatus answers the banner says connecting");
bus.AnswerStatus(Online());
Check(sync.Current().enabled && sync.Current().registered && sync.Current().smsc == "+447785016005" && sync.Current().ownNumber == "+31612345678" && sync.Current().simOperator == "20408", "GetStatus fills the status");
Check(sync.CountryCode() == "31", "the country code comes from the subscriber's own number, not the foreign service centre's");
Check(sync.Plan() == SimPlan{ "31", "20408" }, "the SIM's plan is that code and the status's operator");
Check(CanSend(sync.Current()) && BannerText(sync.Current()).empty(), "online: no banner, can send");
bus.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-1-1", "+31621308050", "already here", 1000), Text("ims-sms-in-1-2", "+31621308050", "new", 1001) });
Check(store.Size() == 2 && events.imported.size() == 1 && events.imported[0].text == "new", "List imports only the text the store lacks");
Check(bus.deletes.size() == 2 && bus.deletes[0].first == "ims-sms-in-1-1" && bus.deletes[1].first == "ims-sms-in-1-2", "imsd's copies are deleted, the known one included");
Check(events.imported[0].conversation == "+31621308050" && !events.imported[0].read, "the import is keyed and unread");
bus.AnswerDelete();
bus.AnswerDelete();
// --- a Received signal: imported once, imsd's copy deleted, a List follows -
sync.OnReceived(Text("ims-sms-in-1-3", "0612345678", "signalled", 1002));
Check(store.Size() == 3 && events.imported.size() == 2 && events.imported[1].conversation == "+31612345678", "a signalled text is imported with the country code");
Check(bus.deletes.size() == 1 && bus.deletes[0].first == "ims-sms-in-1-3", "its copy is deleted");
Check(bus.lists.size() == 1, "a List follows the signal");
bus.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-1-3", "0612345678", "signalled", 1002) });
Check(store.Size() == 3 && bus.deletes.size() == 1, "the same id listed again is neither imported nor deleted twice while its delete is in flight");
bus.AnswerDelete();
sync.OnReceived(Text("ims-sms-in-1-3", "0612345678", "signalled", 1002));
Check(store.Size() == 3 && bus.deletes.size() == 1 && bus.lists.size() == 1, "a repeated signal for a stored id only deletes again");
bus.AnswerDelete();
bus.AnswerList(std::vector<ReceivedMessage>{});
// --- a List during a List is coalesced into one more -------------------------
sync.Refresh();
sync.Refresh();
Check(bus.lists.size() == 1, "a second List while one is in flight waits");
bus.AnswerList(std::vector<ReceivedMessage>{});
Check(bus.lists.size() == 1, "and runs once the first answered");
bus.AnswerList(std::vector<ReceivedMessage>{});
// --- the delete failures -------------------------------------------------------
sync.OnReceived(Text("ims-sms-in-1-4", "+31611111111", "refused", 1003));
bus.AnswerDelete(Error(BusError::Kind::AccessDenied, "not authorized"));
Check(sync.Current().undeletable == 1 && BannerText(sync.Current()) == "imsd still holds 1 message this session may not delete", "a refused delete is counted and shown");
bus.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-1-4", "+31611111111", "refused", 1003) });
Check(bus.deletes.size() == 1 && bus.deletes[0].first == "ims-sms-in-1-4" && sync.Current().undeletable == 0, "a List admitted tries the refused delete again — one action gates both — and the count is off meanwhile");
bus.AnswerDelete(Error(BusError::Kind::AccessDenied, "not authorized"));
Check(sync.Current().undeletable == 1 && bus.deletes.empty(), "refused again: counted again, not tried again until the next List");
sync.OnReceived(Text("ims-sms-in-1-5", "+31611111111", "gone", 1004));
bus.AnswerDelete(Error(BusError::Kind::NotFound, "no such message"));
Check(sync.Current().undeletable == 1 && bus.deletes.empty(), "FileNotFound is done");
bus.AnswerList(std::vector<ReceivedMessage>{});
sync.OnReceived(Text("ims-sms-in-1-6", "+31611111111", "later", 1005));
bus.AnswerDelete(Error(BusError::Kind::Timeout, "timed out"));
bus.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-1-6", "+31611111111", "later", 1005) });
Check(bus.deletes.size() == 1 && bus.deletes[0].first == "ims-sms-in-1-6" && store.Size() == 6, "a timed-out delete is retried by the next list, without a second import");
bus.AnswerDelete();
// --- a conversation on screen is read at once ---------------------------------
sync.SetOpenConversation("+31611111111");
sync.OnReceived(Text("ims-sms-in-1-7", "+31611111111", "while open", 1006));
Check(events.imported.back().read, "a text for the open conversation is stored read");
bus.AnswerDelete();
bus.AnswerList(std::vector<ReceivedMessage>{});
sync.SetOpenConversation(std::nullopt);
// --- a send through its states --------------------------------------------------
events.changed.clear();
const std::uint64_t ours = sync.Send("+31621308050", "+31621308050", "hello");
Check(store.Get(ours) && store.Get(ours)->state == MessageState::Pending && store.Get(ours)->direction == Direction::Outgoing && store.Get(ours)->read, "Send stores a pending outgoing message");
Check(bus.sends.size() == 1 && bus.sends[0].number == "+31621308050" && bus.sends[0].text == "hello" && bus.sends[0].statusReport, "Send asks imsd with a status report");
bus.AnswerSend(std::string("ims-sms-1"));
Check(store.Get(ours)->imsdId == "ims-sms-1", "the id is recorded");
sync.OnStateChanged("ims-sms-1", "sent", "2026-10-17T00:48:32+02:00");
Check(store.Get(ours)->state == MessageState::Sent && store.Get(ours)->stateReason == "2026-10-17T00:48:32+02:00", "sent");
sync.OnStateChanged("ims-sms-1", "delivered", "");
Check(store.Get(ours)->state == MessageState::Delivered, "delivered");
Check(!events.changed.empty() && events.changed.back().id == ours && events.changed.back().state == MessageState::Delivered, "every step reached the listener");
sync.OnStateChanged("ims-sms-99", "sent", "");
Check(!events.logs.empty() && events.logs.back().contains("not on record"), "a state for an unknown id is logged");
sync.OnStateChanged("ims-sms-1", "teleported", "");
Check(events.logs.back().contains("unknown state") && store.Get(ours)->state == MessageState::Delivered, "an unknown state is logged and ignored");
// imsd gives the words in order (its §8.4): each applies as it comes, a
// text of several parts included (imsd holds a report on one part until
// the submission ends and posts it after sent).
const std::uint64_t parts = sync.Send("+31621308050", "+31621308050", "a text long enough for two parts");
bus.AnswerSend(std::string("ims-sms-44"));
sync.OnStateChanged("ims-sms-44", "sent", "2026-10-17T00:49:00+02:00");
sync.OnStateChanged("ims-sms-44", "delivery-pending", "TP-ST 0x30");
Check(store.Get(parts)->state == MessageState::DeliveryPending && store.Get(parts)->stateReason == "TP-ST 0x30" && events.changed.back().state == MessageState::DeliveryPending, "a report's word after sent applies, with its reason, and is announced");
sync.OnStateChanged("ims-sms-44", "delivery-failed", "TP-ST 0x40");
Check(store.Get(parts)->state == MessageState::DeliveryFailed && store.Get(parts)->stateReason == "TP-ST 0x40", "and so does the centre's last word");
// imsd's own failed is the message's last word from imsd (it forgets the
// failed submission's parts): the retry goes under a new id.
const std::uint64_t half = sync.Send("+31621308050", "+31621308050", "two parts, the second refused");
bus.AnswerSend(std::string("ims-sms-45"));
sync.OnStateChanged("ims-sms-45", "failed", "segment 2/2 refused by the SC: RP cause 38");
Check(store.Get(half)->state == MessageState::Failed && store.Get(half)->stateReason == "segment 2/2 refused by the SC: RP cause 38", "imsd's failed applies with its reason");
sync.Retry(half);
Check(store.Get(half)->state == MessageState::Pending && store.Get(half)->imsdId.empty() && bus.sends.size() == 1, "the retry submits it again, without the failed attempt's id");
bus.AnswerSend(std::string("ims-sms-46"));
sync.OnStateChanged("ims-sms-46", "sent", "");
sync.OnStateChanged("ims-sms-46", "delivered", "");
Check(store.Get(half)->state == MessageState::Delivered, "sent and delivered under the new id");
// A retry that never reaches imsd: the failed attempt's id leaves the
// row with the retry, so a word under it (none is due: imsd forgot the
// attempt) finds no row.
const std::uint64_t again = sync.Send("+31621308050", "+31621308050", "two parts, retried while unregistered");
bus.AnswerSend(std::string("ims-sms-47"));
sync.OnStateChanged("ims-sms-47", "failed", "segment 2/2 refused by the SC: RP cause 38");
sync.OnRegistrationChanged(false);
sync.Retry(again);
Check(store.Get(again)->state == MessageState::Failed && store.Get(again)->imsdId.empty() && bus.sends.empty(), "a retry while unregistered fails locally, without the old attempt's id");
sync.OnStateChanged("ims-sms-47", "delivery-pending", "TP-ST 0x30");
Check(store.Get(again)->state == MessageState::Failed && events.logs.back().contains("not on record"), "the old attempt's late report finds no row: the failed and its retry stay");
sync.OnRegistrationChanged(true);
bus.AnswerStatus(Online());
bus.AnswerStatus(Online());
sync.Retry(again);
Check(store.Get(again)->state == MessageState::Pending && bus.sends.size() == 1, "registered again, the retry goes to imsd");
bus.AnswerSend(std::string("ims-sms-48"));
sync.OnStateChanged("ims-sms-48", "sent", "");
Check(store.Get(again)->state == MessageState::Sent, "under its new id");
// --- the destination is the address as dialled; the key groups --------------------
const std::uint64_t dialled = sync.Send("+31612345678", "0612345678", "to the number as typed");
Check(bus.sends.size() == 1 && bus.sends[0].number == "0612345678" && store.Get(dialled)->peer == "0612345678" && store.Get(dialled)->conversation == "+31612345678", "imsd is asked for the address as dialled; the key only groups");
bus.AnswerSend(std::string("ims-sms-5"));
sync.OnStateChanged("ims-sms-5", "sent", "");
Check(store.Get(dialled)->state == MessageState::Sent, "and the state lands under the key");
// --- a failed send and its retry ----------------------------------------------------
const std::uint64_t failed = sync.Send("+31621308050", "+31621308050", "again");
bus.AnswerSend(std::unexpected(Error(BusError::Kind::Timeout, "no reply")));
Check(store.Get(failed)->state == MessageState::Failed && store.Get(failed)->stateReason == "no reply", "a send error fails the message with the reason");
sync.Retry(failed);
Check(store.Get(failed)->state == MessageState::Pending && bus.sends.size() == 1 && bus.sends[0].text == "again", "Retry submits the same message again");
bus.AnswerSend(std::string("ims-sms-2"));
sync.OnStateChanged("ims-sms-2", "failed", "RP-ERROR cause 38");
Check(store.Get(failed)->state == MessageState::Failed && store.Get(failed)->stateReason == "RP-ERROR cause 38", "imsd's failed state lands with its reason");
sync.Retry(ours);
Check(bus.sends.empty(), "a delivered message cannot be retried");
// --- registration and imsd vanishing ---------------------------------------------
sync.OnRegistrationChanged(false);
Check(!CanSend(sync.Current()) && BannerText(sync.Current()) == "Not registered with the IMS network", "unregistered: banner, no send");
Check(bus.statuses.size() == 1, "an unregistration reads the status again too: an answer on its way may carry the state before the signal");
const std::uint64_t refused = sync.Send("+31621308050", "+31621308050", "while unregistered");
Check(store.Get(refused)->state == MessageState::Failed && store.Get(refused)->stateReason == "Not registered with the IMS network" && bus.sends.empty(), "a send while unregistered fails at once with the banner's reason");
Status unregistered = Online();
unregistered.registered = false;
bus.AnswerStatus(unregistered);
Check(!sync.Current().registered, "the re-read keeps the unregistered state");
sync.OnRegistrationChanged(true);
Check(bus.statuses.size() == 1, "a registration reads the status again");
bus.AnswerStatus(Online());
const std::uint64_t inFlight = sync.Send("+31621308050", "+31621308050", "in flight");
bus.AnswerSend(std::string("ims-sms-3"));
sync.OnImsdVanished();
Check(store.Get(inFlight)->state == MessageState::Failed && store.Get(inFlight)->stateReason == "imsd stopped before confirming", "imsd vanishing fails the message in flight");
Check(!sync.Current().imsdPresent && BannerText(sync.Current()) == "imsd is not running", "vanished: the banner says so");
// --- imsd back: Subscribe again; a refused Subscribe is the degraded mode -----------
sync.OnImsdAppeared();
Check(bus.subscribes.size() == 1, "Subscribe again when imsd reappears");
bus.AnswerSubscribe(Error(BusError::Kind::AccessDenied, "not the active session"));
Check(sync.Current().subscribeDenied && !sync.Current().subscribed, "a refused Subscribe is remembered");
bus.AnswerStatus(Online());
Check(BannerText(sync.Current()) == "No live updates: imsd refused this session (polkit)" && !CanSend(sync.Current()), "the degraded banner wins over an online status");
Check(bus.lists.size() == 1, "List is still tried");
bus.AnswerList(std::unexpected(Error(BusError::Kind::AccessDenied, "not the active session")));
Check(events.logs.back().contains("List failed"), "a refused List is logged");
// The session active again: Refresh (main's 30 s timer, RefreshWanted)
// subscribes again, and an admitted Subscribe ends the degraded mode.
Check(sync.RefreshWanted(), "a refusal wants a refresh");
sync.Refresh();
Check(bus.subscribes.size() == 1, "Refresh subscribes again after a refused Subscribe");
sync.Refresh();
Check(bus.subscribes.size() == 1, "and not again over that one unanswered: a rule that prompts is asked once");
bus.AnswerSubscribe();
Check(sync.Current().subscribed && !sync.Current().subscribeDenied, "admitted: the degraded mode ends");
bus.AnswerStatus(Online());
Check(CanSend(sync.Current()) && BannerText(sync.Current()).empty() && bus.lists.size() == 1, "sending is on again and the list is read");
// A List refused while subscribed is the degraded mode too; the next
// List answered lifts it.
bus.AnswerList(std::unexpected(Error(BusError::Kind::AccessDenied, "not the active session")));
Check(sync.Current().subscribeDenied && !CanSend(sync.Current()) && sync.RefreshWanted(), "a refused List turns sending off and wants a refresh");
sync.Refresh();
Check(bus.lists.size() == 1, "Refresh lists again");
const std::size_t announced = events.statuses.size();
bus.AnswerList(std::unexpected(Error(BusError::Kind::AccessDenied, "not the active session")));
Check(events.statuses.size() == announced + 1 && sync.RefreshWanted(), "refused again: announced again, and a refresh is still wanted");
sync.Refresh();
Check(bus.lists.size() == 1, "and Refresh lists once more");
bus.AnswerList(std::vector<ReceivedMessage>{});
Check(!sync.Current().subscribeDenied && CanSend(sync.Current()), "a List answered ends it");
// --- what failed is tried again: a Subscribe that timed out, a GetStatus that failed -------
{
const fs::path retryDir = fs::temp_directory_path() / "imsd-messages-sync-retry";
fs::remove_all(retryDir);
MessageStore retryStore(retryDir);
Fake bus5;
Recorder events5;
Sync retrying(retryStore, bus5, events5);
retrying.OnImsdAppeared();
bus5.AnswerSubscribe(Error(BusError::Kind::Timeout, "no reply"));
Check(retrying.Current().subscribeFailed && !retrying.Current().subscribed && !retrying.Current().subscribeDenied, "a Subscribe that timed out is a failure, not the refusal");
bus5.AnswerStatus(std::unexpected(Error(BusError::Kind::Timeout, "no reply")));
bus5.AnswerList(std::vector<ReceivedMessage>{});
Check(!retrying.Current().statusKnown && retrying.RefreshWanted(), "after a failed GetStatus the status is unknown and a refresh is wanted");
retrying.Refresh();
Check(bus5.subscribes.size() == 1 && bus5.statuses.empty(), "Refresh subscribes again first");
bus5.AnswerSubscribe();
Check(retrying.Current().subscribed && !retrying.Current().subscribeFailed, "the second Subscribe holds");
Status noSmsc = Online();
noSmsc.ownNumber = "";
noSmsc.smsc = "";
bus5.AnswerStatus(noSmsc);
bus5.AnswerList(std::vector<ReceivedMessage>{});
Check(retrying.Current().statusKnown && !retrying.RefreshWanted() && retrying.CountryCode().empty(), "the status is known, without a number yet");
// A List that failed without a refusal (it timed out) is tried again too.
retrying.Refresh();
const std::size_t told = events5.statuses.size();
bus5.AnswerList(std::unexpected(Error(BusError::Kind::Timeout, "no reply")));
Check(retrying.RefreshWanted() && events5.statuses.size() == told + 1 && !retrying.Current().subscribeDenied, "a List that timed out wants a refresh, and says so: the texts imsd holds are asked for again");
retrying.Refresh();
Check(bus5.lists.size() == 1 && bus5.subscribes.empty() && bus5.statuses.empty(), "Refresh lists again, and nothing else");
bus5.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-5-1", "+31621308050", "held by imsd", 1200) });
Check(!retrying.RefreshWanted() && events5.imported.size() == 1, "answered: the held text is imported and no refresh is wanted");
bus5.AnswerDelete();
retrying.OnRegistrationChanged(true);
Check(bus5.statuses.size() == 1 && bus5.subscribes.empty(), "a registration reads the status again");
Status centreOnly = Online();
centreOnly.ownNumber = "";
bus5.AnswerStatus(centreOnly);
Check(retrying.CountryCode() == "44" && retrying.Plan().code.empty(), "without an own number the service centre's code stands in for a key, and the plan has no code");
retrying.OnRegistrationChanged(true);
bus5.AnswerStatus(Online());
Check(retrying.CountryCode() == "31" && retrying.Plan().code == "31", "the own number, once read, gives the code, and it is the plan's");
retrying.OnRegistrationChanged(true);
bus5.AnswerStatus(centreOnly);
Check(retrying.CountryCode() == "44" && retrying.Plan().code.empty(), "a read without it: the centre's stands in again and the plan has no code (imsd gives both from one snapshot, so a number it has is never missing)");
retrying.OnRegistrationChanged(true);
bus5.AnswerStatus(std::unexpected(Error(BusError::Kind::Timeout, "no reply")));
Check(retrying.RefreshWanted() && retrying.Current().statusKnown, "a later GetStatus failure keeps what was known and wants a refresh");
retrying.Refresh();
Check(bus5.statuses.size() == 1 && bus5.lists.size() == 1, "Refresh reads the status and the list again");
bus5.AnswerStatus(Online());
bus5.AnswerList(std::vector<ReceivedMessage>{});
Check(!retrying.RefreshWanted(), "and nothing is wanted once both answered");
fs::remove_all(retryDir);
}
Store, Sync, main: a deleted text stays deleted imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
2026-11-01 18:11:01 +01:00
// --- a message deleted while it is sending: imsd's late answers write nothing -------------
{
const fs::path deletedDir = fs::temp_directory_path() / "imsd-messages-sync-deleted";
fs::remove_all(deletedDir);
MessageStore deletedStore(deletedDir);
Fake bus6;
Recorder events6;
Sync deleting(deletedStore, bus6, events6, "31");
deleting.OnImsdAppeared();
bus6.AnswerSubscribe();
bus6.AnswerStatus(Online());
bus6.AnswerList(std::vector<ReceivedMessage>{});
// A delivered message of an earlier imsd run: its id is its own, and
// no later Send gets it (imsd's ids are unique across its runs).
Message earlier;
earlier.conversation = "+31621308050";
earlier.peer = "+31621308050";
earlier.direction = Direction::Outgoing;
earlier.text = "from an earlier imsd run";
earlier.sortTime = earlier.received = 900;
earlier.state = MessageState::Delivered;
earlier.read = true;
earlier.imsdId = "ims-sms-1700000000-20";
const std::uint64_t older = *deletedStore.Add(earlier);
const std::uint64_t sent = deleting.Send("+31621308050", "+31621308050", "deleted while it is sending");
bus6.AnswerSend(std::string("ims-sms-1700000900-1"));
deleting.Erase(sent);
deleting.OnStateChanged("ims-sms-1700000900-1", "sent", "");
deleting.OnStateChanged("ims-sms-1700000900-1", "delivery-failed", ""); // the report after the sent, for a deleted message
Check(!deletedStore.Get(sent) && deletedStore.Size() == 1, "a message deleted after imsd took it stays deleted when its state comes");
const std::uint64_t early = deleting.Send("+31621308050", "+31621308050", "deleted before imsd answered");
deleting.Erase(early);
bus6.AnswerSend(std::string("ims-sms-1700000900-2"));
deleting.OnStateChanged("ims-sms-1700000900-2", "sent", "");
const std::uint64_t failing = deleting.Send("+31621308051", "+31621308051", "in a conversation deleted before imsd answered");
deleting.EraseConversation("+31621308051");
bus6.AnswerSend(std::unexpected(Error(BusError::Kind::Other, "late failure")));
Check(deletedStore.Size() == 1 && !deletedStore.Get(early) && !deletedStore.Get(failing), "a deleted message stays deleted when imsd's answer to its Send comes");
Check(std::ranges::count_if(events6.logs, [](const std::string& l) { return l.contains("after it was deleted"); }) == 2 && std::ranges::count_if(events6.logs, [](const std::string& l) { return l.contains("not on record"); }) == 3, "each late answer is logged: the Send answers as deleted, the states as not on record");
// A received text deleted while imsd still holds its copy (polkit
// refused the delete) is not imported again by a later List; once
// imsd no longer lists it, it is forgotten.
deleting.Refresh();
bus6.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-9-1", "+31621308052", "kept by imsd", 950) });
const std::vector<Message> conv9 = deletedStore.Conversation("+31621308052");
Check(conv9.size() == 1, "the text is imported");
bus6.AnswerDelete(Error(BusError::Kind::AccessDenied, "not authorized"));
deleting.Erase(conv9[0].id);
Check(deletedStore.ErasedImsdIds().contains("ims-sms-in-9-1"), "its imsd id is remembered when the user deletes it");
deleting.Refresh();
bus6.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-9-1", "+31621308052", "kept by imsd", 950) });
Check(deletedStore.Conversation("+31621308052").empty(), "listed again, it is not imported again");
// A text deleted while a List is in flight: that List's answer is
// older than the memory and does not forget it — it forgets the id
// remembered before it went out; the next one forgets that one too.
deleting.Refresh(); // ims-sms-in-9-1 is remembered as this List goes out
deleting.OnReceived(Text("ims-sms-in-9-2", "+31621308053", "in flight", 960));
const std::vector<Message> conv9b = deletedStore.Conversation("+31621308053");
Check(conv9b.size() == 1, "a text signalled while a List is in flight is imported");
bus6.AnswerDelete(Error(BusError::Kind::AccessDenied, "not authorized"));
deleting.Erase(conv9b[0].id);
bus6.AnswerList(std::vector<ReceivedMessage>{});
Check(!deletedStore.ErasedImsdIds().contains("ims-sms-in-9-1") && deletedStore.ErasedImsdIds().contains("ims-sms-in-9-2"), "the List sent before the delete forgets the id remembered before it went out, not the one remembered while it was in flight");
bus6.AnswerList(std::vector<ReceivedMessage>{});
Check(!deletedStore.ErasedImsdIds().contains("ims-sms-in-9-2"), "the next List, sent after it, forgets that one too");
// Another client's text (imsd tells every subscriber every state):
// its id is on no record here, and the older message keeps its state.
deleting.OnStateChanged("ims-sms-1700000900-3", "failed", "RP-ERROR cause 38");
Check(deletedStore.Get(older) && deletedStore.Get(older)->state == MessageState::Delivered && events6.logs.back().contains("not on record"), "a state for another client's text is logged and leaves every message alone");
fs::remove_all(deletedDir);
}
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// --- a restart: a pending send of an earlier run is failed at start; a late word applies ---
Message stale;
stale.conversation = "+31621308050";
stale.direction = Direction::Outgoing;
stale.text = "from an earlier run";
stale.state = MessageState::Pending;
stale.imsdId = "ims-sms-8";
const std::uint64_t staleId = *store.Add(stale);
{
Fake bus2;
Recorder events2;
Sync sync2(store, bus2, events2, "");
Check(sync2.CountryCode().empty(), "without imsd no country code is assumed: the store's correspondents do not say where the subscriber is, and a typed national number stays national");
Check(store.Get(staleId)->state == MessageState::Failed && store.Get(staleId)->stateReason == "the app stopped before imsd confirmed it", "a pending message from an earlier run is failed at start");
sync2.OnStateChanged("ims-sms-3", "sent", "late");
Check(store.Get(inFlight)->state == MessageState::Sent, "a state for an id found in the store is applied after a restart");
sync2.OnStateChanged("ims-sms-8", "delivery-pending", "TP-ST 0x30");
Check(store.Get(staleId)->state == MessageState::DeliveryPending, "a report's word after the app's own failed applies: imsd knew better");
}
Sync overridden(store, bus, events, "49");
Check(overridden.CountryCode() == "49" && overridden.Plan().code == "49", "the override wins, and is the plan's code");
// --- a copy polkit refused to delete: counted, and tried again once imsd is back ----------
{
const fs::path refusedDir = fs::temp_directory_path() / "imsd-messages-sync-refused";
fs::remove_all(refusedDir);
MessageStore refusedStore(refusedDir);
Fake bus4;
Recorder events4;
Sync refusing(refusedStore, bus4, events4, "31");
refusing.OnImsdAppeared();
bus4.AnswerSubscribe();
bus4.AnswerStatus(Online());
bus4.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-7-1", "+31621308050", "kept by imsd", 1200) });
bus4.AnswerDelete(Error(BusError::Kind::AccessDenied, "not the active session"));
Check(refusing.Current().undeletable == 1, "a copy polkit refused to delete is counted");
refusing.OnImsdVanished();
refusing.OnImsdAppeared();
bus4.AnswerSubscribe();
bus4.AnswerStatus(Online());
bus4.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-7-1", "+31621308050", "kept by imsd", 1200) });
Check(bus4.deletes.size() == 1 && bus4.deletes[0].first == "ims-sms-in-7-1", "once imsd is back its delete is tried again");
bus4.AnswerDelete(Error(BusError::Kind::AccessDenied, "not the active session"));
Check(refusing.Current().undeletable == 1, "and a second refusal is counted again");
fs::remove_all(refusedDir);
}
// --- a row's plan is the SIM's it was written under: under another SIM's, a retry sends nothing ---
{
const fs::path planDir = fs::temp_directory_path() / "imsd-messages-sync-plan";
fs::remove_all(planDir);
MessageStore planStore(planDir);
Fake bus9;
Recorder events9;
Sync plan(planStore, bus9, events9);
plan.OnImsdAppeared();
bus9.AnswerSubscribe();
bus9.AnswerStatus(Online());
bus9.AnswerList(std::vector<ReceivedMessage>{});
const std::uint64_t national = plan.Send("+31612345678", "0612345678", "typed at home");
bus9.AnswerSend(std::string("ims-sms-plan-1"));
plan.OnStateChanged("ims-sms-plan-1", "failed", "RP-ERROR cause 38");
const std::uint64_t shortCode = plan.Send("1234", "1234", "STOP");
bus9.AnswerSend(std::string("ims-sms-plan-2"));
plan.OnStateChanged("ims-sms-plan-2", "failed", "RP-ERROR cause 38");
Check(planStore.Get(national)->plan == SimPlan{ "31", "20408" } && planStore.Get(shortCode)->plan == SimPlan{ "31", "20408" }, "a sent row records the SIM's plan: the code and the operator");
Status standIn = Online();
standIn.ownNumber = "";
plan.OnRegistrationChanged(true);
bus9.AnswerStatus(standIn);
Check(plan.Plan() == SimPlan{ "", "20408" } && plan.CountryCode() == "44", "the same SIM with its own number unread: the centre's code stands in for a key, and the plan has none");
plan.Retry(shortCode);
Check(bus9.sends.size() == 1 && bus9.sends[0].number == "1234", "under the same operator the plan is the same, its code known or not: the retry goes");
bus9.AnswerSend(std::string("ims-sms-plan-3"));
plan.OnStateChanged("ims-sms-plan-3", "failed", "RP-ERROR cause 38");
Status otherOperator = Online();
otherOperator.simOperator = "20404";
plan.OnRegistrationChanged(true);
bus9.AnswerStatus(otherOperator);
plan.Retry(shortCode);
Check(planStore.Get(shortCode)->state == MessageState::Failed && planStore.Get(shortCode)->stateReason == "the number was dialled under another SIM's plan: send it again" && bus9.sends.empty(), "a short code is its operator's: under another operator of the same country a retry sends nothing and says why");
plan.Retry(national);
Check(bus9.sends.size() == 1 && bus9.sends[0].number == "0612345678", "a national number means the same under another operator of its country: the retry goes");
bus9.AnswerSend(std::string("ims-sms-plan-4"));
plan.OnStateChanged("ims-sms-plan-4", "failed", "RP-ERROR cause 38");
Status abroad = Online();
abroad.ownNumber = "+4915112345678";
abroad.simOperator = "26201";
plan.OnRegistrationChanged(true);
bus9.AnswerStatus(abroad);
Check(plan.Plan() == SimPlan{ "49", "26201" }, "another country's SIM: another code and another operator");
plan.Retry(national);
Check(planStore.Get(national)->state == MessageState::Failed && planStore.Get(national)->stateReason == "the number was dialled under another SIM's plan: send it again" && bus9.sends.empty(), "a retry of a national number under another SIM's plan sends nothing and says why");
fs::remove_all(planDir);
}
// --- a text keys itself by the number it arrived for: imported at once, before any status ----------
{
const fs::path earlyDir = fs::temp_directory_path() / "imsd-messages-sync-early";
fs::remove_all(earlyDir);
MessageStore earlyStore(earlyDir);
Fake bus11;
Recorder events11;
Sync earlySync(earlyStore, bus11, events11, "");
earlySync.OnImsdAppeared();
bus11.AnswerSubscribe();
Check(bus11.statuses.size() == 1 && bus11.lists.size() == 1, "Subscribe's answer asks for the status and the List at once");
ReceivedMessage early = Text("ims-sms-in-11-1", "0612345678", "early", 1300);
early.to = "+4915112345678";
early.simOperator = "26201";
earlySync.OnReceived(early);
Check(events11.imported.size() == 1 && events11.imported[0].conversation == "+49612345678" && events11.imported[0].plan == SimPlan{ "49", "26201" } && earlyStore.Size() == 1, "a text signalled before the status's answer is imported at once, keyed and planned by the number it arrived for and the SIM it arrived under");
earlySync.OnReceived(Text("ims-sms-in-11-2", "0612345678", "no own number at receipt", 1301));
Check(events11.imported.size() == 2 && events11.imported[1].conversation == "+31612345678" && events11.imported[1].plan == SimPlan{}, "one that arrived under no own number: keyed by the centre that delivered it, and no code in its plan");
bus11.AnswerStatus(Online());
bus11.AnswerList(std::vector<ReceivedMessage>{ early });
Check(events11.imported.size() == 2 && earlyStore.Size() == 2, "the List imports a signalled text no second time");
fs::remove_all(earlyDir);
}
// --- a short message type 0: imsd acknowledged it, the app discards it ----------
{
const fs::path silentDir = fs::temp_directory_path() / "imsd-messages-sync-type0";
fs::remove_all(silentDir);
MessageStore silentStore(silentDir);
Fake bus12;
Recorder events12;
Sync silentSync(silentStore, bus12, events12);
silentSync.OnImsdAppeared();
bus12.AnswerSubscribe();
bus12.AnswerStatus(Online());
ReceivedMessage silent = Text("ims-sms-in-12-1", "+31621308050", "", 1400);
silent.pid = 0x40;
bus12.AnswerList(std::vector<ReceivedMessage>{ silent, Text("ims-sms-in-12-2", "+31621308050", "a text", 1401) });
Check(silentStore.Size() == 1 && events12.imported.size() == 1 && events12.imported[0].text == "a text", "a short message type 0 is neither stored nor announced");
Check(bus12.deletes.size() == 2 && bus12.deletes[0].first == "ims-sms-in-12-1", "and imsd's copy of it is deleted like any other");
bus12.AnswerDelete();
bus12.AnswerDelete();
silent.imsdId = "ims-sms-in-12-3";
silentSync.OnReceived(silent);
Check(silentStore.Size() == 1 && events12.imported.size() == 1 && bus12.deletes.size() == 1 && bus12.deletes[0].first == "ims-sms-in-12-3", "one that comes as a signal: the same");
fs::remove_all(silentDir);
}
// --- a listener throwing out of a word is caught and told; no step of the sequence is lost ----------
{
struct Thrower : Recorder {
bool onStatus = false;
bool onLog = false;
void OnStatus(const AppStatus& s) override {
Recorder::OnStatus(s);
if (std::exchange(onStatus, false)) throw std::runtime_error("a status handler's");
}
void OnLog(std::string_view line) override {
Recorder::OnLog(line);
if (std::exchange(onLog, false)) throw std::runtime_error("a log line's");
}
};
const fs::path throwDir = fs::temp_directory_path() / "imsd-messages-sync-throw";
fs::remove_all(throwDir);
MessageStore throwStore(throwDir);
Fake bus13;
Thrower events13;
Sync throwing(throwStore, bus13, events13, "");
events13.onStatus = true;
throwing.OnImsdAppeared();
Check(bus13.subscribes.size() == 1 && events13.logs.back() == "a listener threw: a status handler's", "a throw out of OnStatus at the appearance is caught and told: Subscribe went out");
events13.onLog = true;
bus13.AnswerSubscribe(Error(BusError::Kind::AccessDenied, "not the active session"));
Check(bus13.statuses.size() == 1 && bus13.lists.size() == 1 && events13.logs.back() == "a listener threw: a log line's", "a throw out of OnLog at a refused Subscribe: the status and the List are asked for all the same");
bus13.AnswerStatus(Online());
bus13.AnswerList(std::vector<ReceivedMessage>{});
events13.onStatus = true;
throwing.OnRegistrationChanged(true);
Check(bus13.statuses.size() == 1 && events13.logs.back() == "a listener threw: a status handler's", "a throw out of OnStatus at a registration change: the status is read again");
bus13.AnswerStatus(Online());
events13.onStatus = true;
events13.onLog = true;
throwing.OnImsdVanished();
Check(!throwing.Current().imsdPresent && events13.logs.back() == "a listener threw: a status handler's", "a word of the fault that throws too is dropped, and the vanish went through");
// A store that refused before a Sync was made on it: the
// constructor's status goes through the guard as every word does.
const rlimit before = FillUntilRefused(throwStore, throwDir);
Fake bus14;
Thrower events14;
events14.onStatus = true;
Sync late(throwStore, bus14, events14, "");
setrlimit(RLIMIT_FSIZE, &before);
Check(late.Current().storeFailed && events14.statuses.size() == 1 && events14.logs.back() == "a listener threw: a status handler's", "a throw out of OnStatus at the constructor, over a store that refuses: caught and told");
fs::remove_all(throwDir);
}
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
// --- the --send errand: it sends, and leaves imsd's texts to the instance --------------
{
const fs::path errandDir = fs::temp_directory_path() / "imsd-messages-sync-errand";
fs::remove_all(errandDir);
MessageStore errandStore(errandDir);
Fake bus3;
Recorder events3;
Sync errand(errandStore, bus3, events3, "31");
errand.LeaveTexts();
errand.OnImsdAppeared();
bus3.AnswerSubscribe();
Check(bus3.statuses.size() == 1 && bus3.lists.empty(), "the errand asks for the status and lists nothing");
bus3.AnswerStatus(Online());
errand.OnReceived(Text("ims-sms-in-9-1", "+31621308050", "for the instance", 1100));
Check(errandStore.Size() == 0 && bus3.deletes.empty() && bus3.lists.empty(), "a signalled text is neither imported nor deleted by the errand");
const std::uint64_t sent = errand.Send("+31621308050", "+31621308050", "from the errand", true);
Check(bus3.sends.size() == 1 && bus3.sends[0].text == "from the errand", "the errand sends");
bus3.AnswerSend(std::string("ims-sms-9"));
// imsd's words reach the listener as the message's changes, as they
// come, the submission's first (imsd's order); the errand ends on it.
errand.OnStateChanged("ims-sms-9", "sent", "");
errand.OnStateChanged("ims-sms-9", "delivery-pending", "TP-ST 0x30");
std::vector<MessageState> seen; // the message's states as announced (the pending's announcements — the Send's, the id's — collapsed)
for (const Message& m : events3.changed) if (m.id == sent) seen.push_back(m.state);
seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
Check(seen == std::vector<MessageState>{ MessageState::Pending, MessageState::Sent, MessageState::DeliveryPending } && errandStore.Get(sent)->state == MessageState::DeliveryPending, "imsd's words reach the listener as the message's changes, as they come, and the store follows them");
// Unregistered: a send fails at once, a forced one goes to imsd.
errand.OnRegistrationChanged(false);
const std::uint64_t local = errand.Send("+31621308050", "+31621308050", "not forced");
Check(errandStore.Get(local)->state == MessageState::Failed && bus3.sends.empty(), "unregistered, a send fails without asking imsd");
const std::uint64_t forced = errand.Send("+31621308050", "+31621308050", "forced", true);
Check(bus3.sends.size() == 1 && bus3.sends[0].text == "forced", "a forced send goes to imsd all the same");
bus3.AnswerSend(std::unexpected(Error(BusError::Kind::Other, "imsd is not registered")));
Check(errandStore.Get(forced)->state == MessageState::Failed && errandStore.Get(forced)->stateReason == "imsd is not registered", "and fails with imsd's reason");
fs::remove_all(errandDir);
}
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// --- the store refusing a write: the file-size limit stands in for a full disk ------------
{
const fs::path fullDir = fs::temp_directory_path() / "imsd-messages-sync-full";
fs::remove_all(fullDir);
MessageStore fullStore(fullDir);
Fake bus8;
Recorder events8;
Sync full(fullStore, bus8, events8, "31");
full.OnImsdAppeared();
bus8.AnswerSubscribe();
bus8.AnswerStatus(Online());
bus8.AnswerList(std::vector<ReceivedMessage>{});
const rlimit before = FillUntilRefused(fullStore, fullDir);
const std::size_t announced = events8.statuses.size();
Check(fullStore.Refused() && full.Current().storeFailed && full.RefreshWanted() && announced > 0 && events8.statuses.back().storeFailed && events8.logs.back().contains("the store refused a write"), "the store's refusal reaches the status: the banner's flag, a Refresh wanted, the log");
const std::string longText(4096, 'y'); // the room left after the filler holds no text of this size (a short one might still fit)
Check(full.Send("+31621308050", "+31621308050", longText) == Sync::kNotStored && bus8.sends.empty() && events8.statuses.size() == announced, "a send the store refused answers kNotStored and asks imsd nothing");
full.OnImsdVanished();
full.OnImsdAppeared();
bus8.AnswerSubscribe();
bus8.AnswerStatus(Online());
bus8.AnswerList(std::vector<ReceivedMessage>{});
Check(full.Current().storeFailed && full.RefreshWanted(), "imsd's restart does not forget the store's refusal: the flag is the store's");
full.Refresh(); // what main's 30 s timer does while a Refresh is wanted
bus8.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-8-1", "+31621308050", longText, 1300) });
Check(bus8.deletes.empty() && events8.imported.empty() && events8.unstored.empty() && full.Current().storeFailed && full.RefreshWanted(), "an import the store refused leaves imsd's copy: nothing deleted, nothing announced — a listed text is not held —, the banner still up and a Refresh still wanted");
// A short text fits the room the store has (every string inline, a
// row slot free): it goes, the flag standing — nothing grew — and
// imsd's id lands in place, inline in the row.
const std::uint64_t shortOne = full.Send("+31621308050", "+31621308050", "ok");
Check(shortOne != Sync::kNotStored && bus8.sends.size() == 1 && full.Current().storeFailed && full.RefreshWanted(), "a short text's row fits: it goes to imsd, and the flag stands, nothing having grown");
bus8.AnswerSend(std::string("ims-sms-8a1b2c3d-1793559285-1"));
Check(fullStore.Get(shortOne)->imsdId == "ims-sms-8a1b2c3d-1793559285-1" && fullStore.Refused(), "imsd's id lands in place on the full store");
full.OnStateChanged("ims-sms-8a1b2c3d-1793559285-1", "sent", "2026-11-01T19:00:00+01:00");
Check(fullStore.Get(shortOne)->state == MessageState::Sent && fullStore.Get(shortOne)->stateReason.empty(), "imsd's word lands: the id names the row, the state in place, its reason (needing room) not");
// A failed attempt's id goes at the retry, in place: imsd's words for
// the new attempt name the row, the old one's none.
const std::uint64_t retried = full.Send("+31621308050", "+31621308050", "re");
bus8.AnswerSend(std::string("ims-sms-8a1b2c3d-1793559285-2"));
full.OnStateChanged("ims-sms-8a1b2c3d-1793559285-2", "failed", "RP-ERROR cause 38");
Check(fullStore.Get(retried)->state == MessageState::Failed && fullStore.Get(retried)->imsdId == "ims-sms-8a1b2c3d-1793559285-2", "a short text's failed word lands on its row");
full.Retry(retried);
Check(bus8.sends.size() == 1 && fullStore.Get(retried)->state == MessageState::Pending && fullStore.Get(retried)->imsdId.empty(), "the retry goes to imsd, the failed attempt's id dropped in place");
bus8.AnswerSend(std::string("ims-sms-8a1b2c3d-1793559285-3"));
full.OnStateChanged("ims-sms-8a1b2c3d-1793559285-2", "sent", "");
Check(fullStore.Get(retried)->state == MessageState::Pending && events8.logs.back().contains("not on record"), "the failed attempt's id went with the retry: its late word names no row");
full.OnStateChanged("ims-sms-8a1b2c3d-1793559285-3", "sent", "");
Check(fullStore.Get(retried)->state == MessageState::Sent, "the retry's id names the row");
setrlimit(RLIMIT_FSIZE, &before);
const std::uint64_t went = full.Send("+31621308050", "+31621308050", longText);
Check(went != Sync::kNotStored && bus8.sends.size() == 1 && !full.Current().storeFailed && !full.RefreshWanted() && !events8.statuses.back().storeFailed, "room again: the send's own write grows the file, clears the flag, and the text goes to imsd");
Check(fullStore.Get(shortOne)->imsdId == "ims-sms-8a1b2c3d-1793559285-1" && fullStore.Get(retried)->imsdId == "ims-sms-8a1b2c3d-1793559285-3", "the ids stand as recorded in place — the retry's, not the failed attempt's");
Check(bus8.lists.size() == 1, "and the recovery lists at once: the held texts wait for no timer");
bus8.AnswerSend(std::string("ims-sms-80"));
bus8.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-8-1", "+31621308050", longText, 1300) });
Check(events8.imported.size() == 1 && bus8.deletes.size() == 1 && bus8.deletes[0].first == "ims-sms-in-8-1", "and the held text is imported and deleted at that List");
fs::remove_all(fullDir);
}
main: the resident daemon mode, the send errand and one instance The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
2026-10-17 23:45:29 +02:00
// --- the --send errand's rule (Sync's SendErrand): one Send, one end -----------------
{
SendErrand e;
AppStatus s;
Check(!e.SendDue(s), "no Send before imsd is there");
s.imsdPresent = true;
Check(!e.SendDue(s), "nor before its status is in");
s.statusKnown = true;
Check(e.SendDue(s) && !e.SendDue(s), "once the status is in: one Send; a second status — one announced from inside Send — makes none");
Check(!e.Sent(7).has_value(), "a stored row is followed, nothing ends");
Message other;
other.id = 8;
other.state = MessageState::Sent;
Check(!e.Changed(other).has_value(), "another message's final state is not the errand's");
Message own;
own.id = 7;
own.state = MessageState::Pending;
Check(!e.Changed(own).has_value(), "a pending change ends nothing");
own.state = MessageState::Sent;
own.stateReason = "2026-11-01T22:00:00+01:00";
const std::optional<SendErrand::End> sent = e.Changed(own);
Check(sent && sent->code == 0 && sent->caption == "Sent" && sent->reason == "2026-11-01T22:00:00+01:00" && e.Done(), "sent: 0, imsd's caption and reason");
Check(!e.TimedOut("60 s").has_value() && !e.NoFinalState("ended before a final state").has_value(), "a final state given first stands: the clock and the loop's end after it change nothing");
own.state = MessageState::Failed;
Check(!e.Changed(own).has_value(), "and over a later word");
SendErrand failing;
failing.SendDue(s);
failing.Sent(9);
Message f;
f.id = 9;
f.state = MessageState::Failed;
f.stateReason = "RP-ERROR cause 38";
const std::optional<SendErrand::End> fe = failing.Changed(f);
Check(fe && fe->code == 1 && fe->caption == "Failed" && fe->reason == "RP-ERROR cause 38", "failed: 1, with imsd's reason");
SendErrand refused;
refused.SendDue(s);
const std::optional<SendErrand::End> re = refused.Sent(Sync::kNotStored);
Check(re && re->code == 1 && re->caption == "Failed" && re->reason == "the store did not take the text" && refused.Done(), "a store that refused the text: 1, ended");
SendErrand early;
const std::optional<SendErrand::End> te = early.TimedOut("60 s");
Check(te && te->code == 2 && te->caption == "imsd did not become ready within 60 s", "the clock before the status: 2, imsd not ready");
Check(!early.SendDue(s), "and no Send after it: a status dispatched after the clock's end makes none");
SendErrand waiting;
waiting.SendDue(s);
waiting.Sent(3);
const std::optional<SendErrand::End> tw = waiting.TimedOut("60 s");
Check(tw && tw->code == 2 && tw->caption == "no final state within 60 s" && !waiting.TimedOut("60 s").has_value(), "the clock after the Send, before imsd's id: 2, no final state — once");
SendErrand taken;
taken.SendDue(s);
taken.Sent(5);
Message t;
t.id = 5;
t.state = MessageState::Pending;
t.imsdId = "ims-sms-5";
Check(!taken.Changed(t).has_value() && !taken.TimedOut("60 s").has_value() && !taken.Done(), "the clock once imsd has taken the text decides nothing: imsd bounds its submission itself");
t.state = MessageState::Sent;
const std::optional<SendErrand::End> ts = taken.Changed(t);
Check(ts && ts->code == 0 && taken.Done(), "and imsd's word ends the errand, however long after");
SendErrand signalled;
signalled.SendDue(s);
signalled.Sent(4);
const std::optional<SendErrand::End> si = signalled.NoFinalState("interrupted before a final state");
Check(si && si->code == 2 && si->caption == "interrupted before a final state", "a signal: 2");
SendErrand ended;
ended.NoFinalState("interrupted before a final state");
Check(!ended.SendDue(s), "nor a Send after a signal's end before any");
}
// The rule end to end, in the shape that sent two texts once: a listener
// running it from OnStatus, over a store refused before and recovering
// inside the Send's own write — which announces a status from inside
// Send. One text to imsd.
{
struct ErrandListener : Recorder {
Sync* sync = nullptr;
SendErrand errand;
std::size_t sends = 0;
void OnStatus(const AppStatus& s) override {
Recorder::OnStatus(s);
if (sync && errand.SendDue(s)) {
++sends;
errand.Sent(sync->Send("+31621308050", "+31621308050", std::string(4096, 'z'), true));
}
}
};
const fs::path reDir = fs::temp_directory_path() / "imsd-messages-sync-reentry";
fs::remove_all(reDir);
MessageStore reStore(reDir);
Fake bus10;
ErrandListener events10;
Sync reSync(reStore, bus10, events10, "31");
events10.sync = &reSync;
reSync.LeaveTexts();
const rlimit before = FillUntilRefused(reStore, reDir);
Check(reStore.Refused(), "the store refused a write");
setrlimit(RLIMIT_FSIZE, &before); // room again: the errand's own write will grow the file and tell of the recovery, from inside Send
reSync.OnImsdAppeared();
bus10.AnswerSubscribe();
bus10.AnswerStatus(Online());
Check(events10.sends == 1 && bus10.sends.size() == 1 && !reStore.Refused() && !events10.errand.Done(), "the status announced from inside the errand's Send makes no second Send: one text to imsd");
fs::remove_all(reDir);
}
Sync: the app's side of the Messaging interface over an abstract transport imsd keeps a received text it could store until the app deletes it and sends its signals unicast to subscribers, so the logic is: Subscribe whenever net.catcrafts.IMS1 appears (imsd's restart empties its list), then GetStatus, whose answer ends the connecting state, and List, both at once — a listed or signalled text keys itself by the number it arrived for (imsd's `to`, the subscriber's own number at receipt) or, lacking one, by the service centre that delivered it (Model's MessageFromReceived), so no import waits for a status; import what the store lacks, keyed by imsd's id (its run's token makes it unique across imsd's runs, §8.4), and delete imsd's copy — again for a copy still listed, so a delete that timed out gets another chance. A short message type 0 (Model's IsType0) is not imported: imsd acknowledged it, and its copy is deleted like any other. A copy polkit refused to delete is counted on the banner and tried again at the next List imsd admits (one polkit action gates List and Delete, so an admitted List means an admitted Delete) and once imsd has restarted. A Received signal imports and lists again, because a signal is queued for nobody. The listener is called through a guard (GuardedListener): a throw out of a handler — a logging failure, a bad_alloc — is caught and told once, so no handler can stop Sync's own sequence, whatever the order of a word and the step after it. A store that refuses a write (its disk full) is on the banner. A listed text stays imsd's — nothing is deleted — and a signalled one is held in memory and told through OnUnstored: imsd signals a text its own store refused too, the signal then its only delivery, so no List may ever carry it; the held text is tried again whenever a List comes back with imsd's texts and at each Refresh, which is wanted while one is held, until its row is in or a List carries it; one imsd did not store is lost with a process that ends before then. Of the refusal itself the store tells Sync of a refusal once and once of the next write that got room (one that grew a file), every write but a Compact passing that one gate, and the flag stays the store's — read again after the start's sweep and after imsd's vanish; a send still goes, its own write a try — refused, it answers kNotStored and the caller keeps the text; through, it goes to imsd, and imsd's id lands in place (the store keeps it inline) — a recovery lists at once and the Refresh lists meanwhile, so the held imports are tried once there is room. A listener's call can come from inside Sync's own (the store's word on a write, inside Send), which the listener interface says. A Send stores the message pending under its conversation key and asks imsd for the address as dialled (the key groups; a country code completed for it is never dialled), the row carrying the plan it is dialled under — the country code of the SIM's own number, never the service centre's stand-in, and its operator, which imsd's status gives — which a retry under another SIM's plan fails on, since the address would reach another subscriber or another service there (Number's AnotherPlan, here with its first caller: the same operator is the same plan, a side's code known or not; under another operator a national number means the same while both SIMs' own numbers have one country code, and a short code is the operator's own; without both operators the codes decide alone), and the StateChanged for its id (unique across imsd's runs by the run's token, so it names one message) moves it on — each word as it comes, imsd giving them in order (the submission's first, a report's after sent; its AGENTS.md section 8.4) — and a retry drops the failed attempt's imsd id (a row's id names its current attempt); a Send's error fails the row and Retry sends the text again, so the transport's contract (ImsdTransport's comment) is that a Send is answered by imsd, or because imsd has left the bus, and never by a clock of the transport's own, since imsd sends what it was asked once its polkit prompt lets the call through, however late; imsd vanishing fails what was in flight, and a message still pending from an earlier run is failed at start, because its answer may have come while the app was not running. A refused Subscribe or List is the degraded mode: the banner says so and sending is off — until Refresh is admitted again, since imsd asks polkit on every gated call and a refusal that held while the session was inactive lifts when it is active (a List answered ends it, a refused Subscribe is made again; every refusal is announced, and RefreshWanted() asks for the Refresh). A Subscribe that fails otherwise, a GetStatus or a List (one that timed out: the texts imsd holds would wait for the next signal) is tried again by Refresh too, which RefreshWanted() asks for — one Subscribe at a time, so a rule that prompts is not asked again while that Subscribe waits on its prompt; a registration change reads the status again, since imsd fills in the subscriber's own number and the service centre's when it registers; the own number's country code completes a typed national number (a received one carries its own), the centre's stands in when the network gave no tel: URI (an MVNO's centre can be abroad); without either a national number stays as typed, since the store's correspondents do not say where the subscriber is. The transport is an interface with callbacks, so the tests' fake can stand in for the bus. Tested: tests/Sync on a fake transport that records every call and answers when told, the retries, the second GetStatus, the as-dialled destination, a retry under another SIM (refused for a national number under another country's and for a short code under another operator of the same country; let through under the same operator, its own number read or not, and for a national number under another operator of its country), the plan's code the own number's or the constructor's override and never the centre's, a short message type 0 left out of the store with imsd's copy deleted, a text signalled before the status's answer imported at once by the number it arrived for, a listener's throw at a status — the constructor's among them, over a store that refuses — a log line and a registration change caught and told, stopping no step, a Refresh over an unanswered Subscribe sending none, a List that timed out listed again, the words applied as they come, a retry under a new id, and a refusal lifted among them; the store's refusal under the file-size limit (the flag, the Refresh wanted and the log; a send answered kNotStored with imsd asked nothing; an import refused leaving imsd's copy with the banner up across imsd's restart; a short text sent through the refusal, imsd's id landing in place and its `sent` with it, a failed attempt's id dropped at the retry; then, room again, the send's own write clearing the flag and the held text imported and deleted at the List the recovery sends); a signalled text the store refuses that no List carries (told as unstored once, unread though its conversation is open, held across a List's answer and a Refresh, stored at the Refresh after there is room, its delete answered NotFound), one a List does carry (the copy held here dropped, the text imported by the next List), and one still held when another write gives the store room (a Refresh wanted for it alone until the recovery's List is answered); a listed text the store refuses is not held.
2026-10-17 23:36:20 +02:00
// --- a signalled text the store refuses: imsd signals a text it could not
// store itself too, so no List may ever carry it — held, told, stored
// when there is room ---------------------------------------------------
{
const fs::path heldDir = fs::temp_directory_path() / "imsd-messages-sync-held";
fs::remove_all(heldDir);
MessageStore heldStore(heldDir);
Fake bus13;
Recorder events13;
Sync holding(heldStore, bus13, events13, "31");
holding.OnImsdAppeared();
bus13.AnswerSubscribe();
bus13.AnswerStatus(Online());
bus13.AnswerList(std::vector<ReceivedMessage>{});
const rlimit before = FillUntilRefused(heldStore, heldDir);
const std::string longText(4096, 'z'); // needs room the full store has not
holding.SetOpenConversation("+31621308050"); // on screen, and told unread all the same: no screen has the text
holding.OnReceived(Text("ims-sms-in-13-1", "+31621308050", longText, 1400));
Check(events13.imported.empty() && events13.unstored.size() == 1 && events13.unstored[0].text == longText && events13.unstored[0].imsdId == "ims-sms-in-13-1" && !events13.unstored[0].read && bus13.deletes.empty() && holding.RefreshWanted(), "a signalled text the store refuses is told as unstored — unread, its conversation open — and held: nothing imported, nothing deleted, a Refresh wanted");
holding.SetOpenConversation(std::nullopt);
bus13.AnswerList(std::vector<ReceivedMessage>{}); // the signal's List: imsd does not hold the text either
holding.Refresh();
bus13.AnswerList(std::vector<ReceivedMessage>{});
Check(events13.unstored.size() == 1 && events13.imported.empty() && !heldStore.FindByImsdId("ims-sms-in-13-1"), "tried again at a List's answer and at a Refresh while the store refuses: still held, told once");
setrlimit(RLIMIT_FSIZE, &before);
holding.Refresh();
Check(events13.imported.size() == 1 && events13.imported[0].text == longText && events13.imported[0].imsdId == "ims-sms-in-13-1" && heldStore.FindByImsdId("ims-sms-in-13-1") && !holding.Current().storeFailed, "room again: the held text is stored at the next Refresh, and the store's flag clears");
Check(bus13.deletes.size() == 1 && bus13.deletes[0].first == "ims-sms-in-13-1", "its delete goes to imsd as any import's");
bus13.AnswerDelete(Error(BusError::Kind::NotFound, "no stored message ims-sms-in-13-1")); // imsd never stored it
bus13.AnswerList(std::vector<ReceivedMessage>{}); // the recovery's List
bus13.AnswerList(std::vector<ReceivedMessage>{}); // the Refresh's own, asked while that one was in flight
Check(events13.imported.size() == 1 && bus13.lists.empty() && !holding.RefreshWanted(), "stored once, and no Refresh is wanted any more");
// A held text a List does carry is imsd's to keep after all: the
// copy held here goes, and the text comes in by the List.
const rlimit again = FillUntilRefused(heldStore, heldDir);
holding.OnReceived(Text("ims-sms-in-13-2", "+31621308050", longText, 1500));
Check(events13.unstored.size() == 2 && events13.imported.size() == 1, "a second signalled text the store refuses is held and told");
bus13.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-13-2", "+31621308050", longText, 1500) });
setrlimit(RLIMIT_FSIZE, &again);
holding.Refresh();
Check(events13.imported.size() == 1 && events13.unstored.size() == 2 && bus13.deletes.empty(), "a List carried it while the store refused: imsd holds it, the copy held here is dropped, and a Refresh's retry imports nothing");
bus13.AnswerList(std::vector<ReceivedMessage>{ Text("ims-sms-in-13-2", "+31621308050", longText, 1500) });
Check(events13.imported.size() == 2 && events13.imported[1].imsdId == "ims-sms-in-13-2" && bus13.deletes.size() == 1 && bus13.deletes[0].first == "ims-sms-in-13-2", "and the next List imports it and deletes imsd's copy");
// A text is held and the store gets room by another write: until
// the List the recovery sends is answered the text is still held,
// and a Refresh is wanted for it alone.
const rlimit third = FillUntilRefused(heldStore, heldDir);
holding.OnReceived(Text("ims-sms-in-13-3", "+31621308050", longText, 1600));
bus13.AnswerList(std::vector<ReceivedMessage>{}); // the signal's List
setrlimit(RLIMIT_FSIZE, &third);
const std::uint64_t sent = holding.Send("+31621308050", "+31621308050", longText); // grows the file: the store's recovery, told from inside the send
Check(sent != Sync::kNotStored && !holding.Current().storeFailed && events13.imported.size() == 2 && holding.RefreshWanted(), "the store writes again by a send's own row: the text is still held, and a Refresh is wanted for it alone");
bus13.AnswerList(std::vector<ReceivedMessage>{}); // the recovery's List
Check(events13.imported.size() == 3 && events13.imported[2].imsdId == "ims-sms-in-13-3" && !holding.RefreshWanted(), "the recovery's List answered: the held text is stored, and no Refresh is wanted");
fs::remove_all(heldDir);
}
fs::remove_all(dir);
return failures == 0 ? 0 : 1;
}