diff --git a/interfaces/ImsdMessages-Number.cppm b/interfaces/ImsdMessages-Number.cppm index 8ef91be..66e83c9 100644 --- a/interfaces/ImsdMessages-Number.cppm +++ b/interfaces/ImsdMessages-Number.cppm @@ -158,6 +158,27 @@ export namespace ImsdMessages { friend bool operator==(const SimPlan&, const SimPlan&) = default; }; + // Whether an address is dialled under another SIM's plan than the one + // it was written under (`then`; `now` is the SIM's as imsd's status + // gives it), where it would reach another subscriber or another + // service. An international address (a leading '+') names its own + // plan. Under the same operator the plan is the same, a side's code + // known or not. Under another operator a number its country's plan + // reads as a subscriber's (NormalizeNumber completes it) means the same + // while both SIMs' own numbers have one country code; anything else — + // a short code, which is the operator's own, or a number where a + // side's code is not known — does not. Without both operators the + // codes decide alone, and nothing is known without both of those. + bool AnotherPlan(std::string_view address, const SimPlan& then, const SimPlan& now) { + if (address.empty() || address[0] == '+') return false; + const bool operators = !then.operatorId.empty() && !now.operatorId.empty(); + if (operators && then.operatorId == now.operatorId) return false; + const bool codes = !then.code.empty() && !now.code.empty(); + if (codes && then.code != now.code) return true; + if (!operators) return false; + return !codes || !IsE164(NormalizeNumber(address, now.code)); + } + // The number as the UI shows it: "+31 612345678" for E.164, the key // itself for everything else. std::string DisplayNumber(std::string_view key) { diff --git a/interfaces/ImsdMessages-Sync.cppm b/interfaces/ImsdMessages-Sync.cppm index 54e99fe..cb45e57 100644 --- a/interfaces/ImsdMessages-Sync.cppm +++ b/interfaces/ImsdMessages-Sync.cppm @@ -1,8 +1,528 @@ // SPDX-License-Identifier: GPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® +/* +ImsdMessages:Sync — the app's side of imsd's Messaging interface, as pure +logic over an abstract transport. + +imsd keeps a received text it could store until the app deletes it: the +app lists at start and after every Received, imports what it lacks, then +deletes imsd's copy. The signals are unicast to subscribers, so Subscribe +goes first, every time net.catcrafts.IMS1 appears on the bus (imsd's +restart empties its list). A Send answers with an id at once; the outcome +is a StateChanged for that id. All of it runs on one thread (the GLib main +loop in the app, the test's thread here); the transport answers through +callbacks, never from inside the call. +*/ export module ImsdMessages:Sync; import std; +import :Number; +import :Model; +import :Store; export namespace ImsdMessages { + struct BusError { + enum class Kind : std::uint8_t { NoOwner, AccessDenied, NotSupported, NotFound, InvalidArgs, Timeout, Other }; + Kind kind = Kind::Other; + std::string message; + }; + + // GetStatus's dictionary (imsd AGENTS.md §8.4), the subscriber's own + // number in it (`ppi`, a tel: URI as the frozen interface gives it; "" + // when the network gave none) and the SIM's operator (`operator`: its + // MCC, then its MNC). No count of the store: GetStatus + // is open to every local account, and a count would tell them when a + // text arrived (imsd 2.0.0); List is the gated way. + struct Status { + bool enabled = false; + std::string smsc; + std::string ownNumber; + std::string simOperator; + bool registered = false; + std::uint32_t subscribers = 0; + }; + + using Done = std::function)>; + using StatusResult = std::expected; + using ListResult = std::expected, BusError>; + using SendResult = std::expected; + + // What Sync needs from the bus. The GDBus client implements it; the + // tests a fake that answers when told to. A Send is answered by imsd, + // or by the bus once imsd has left it, never by a clock of the + // transport's own: Sync fails the row at an error and Retry sends the + // text again, and imsd sends what it was asked once its polkit prompt + // lets the call through, however late. + struct ImsdTransport { + virtual ~ImsdTransport() = default; + virtual void Subscribe(Done done) = 0; + virtual void GetStatus(std::function done) = 0; + virtual void List(std::function done) = 0; + virtual void Delete(std::string id, Done done) = 0; + virtual void Send(std::string number, std::string text, bool statusReport, std::function done) = 0; + }; + + // What the bus delivers; Sync implements it. + struct ImsdEvents { + virtual ~ImsdEvents() = default; + virtual void OnImsdAppeared() = 0; + virtual void OnImsdVanished() = 0; + virtual void OnReceived(const ReceivedMessage& message) = 0; + virtual void OnStateChanged(std::string_view id, std::string_view state, std::string_view reason) = 0; + virtual void OnRegistrationChanged(bool registered) = 0; + }; + + // What Sync tells the UI and the notifier. A call can come from inside + // one of Sync's own — OnStatus from the store's word on a write (Send's + // Add, Retry's, OnStateChanged's), OnMessageChanged from Send — so a + // listener acting on one must not take the call it is inside as + // returned (the --send errand latches before it calls Send). Sync calls + // it through GuardedListener: a throw out of a handler is caught and + // told once, so no handler can stop Sync's own sequence. + struct SyncListener { + virtual ~SyncListener() = default; + virtual void OnStatus(const AppStatus&) {} // the banner's inputs changed + virtual void OnImported(const Message&) {} // a received text entered the store + virtual void OnUnstored(const Message&) {} // a signalled text the store refused: Sync holds it, and it may be nowhere else + virtual void OnMessageChanged(const Message&) {} // a message's state changed + virtual void OnLog(std::string_view) {} + }; + + // The listener as Sync calls it: a throw out of the app's handler (a + // logging failure, a bad_alloc) is caught here, so no step of Sync's + // own sequence is skipped by a word it could not deliver — the fault is + // told to the listener once, through the same guard, and a word that + // fails twice is dropped. + class GuardedListener : public SyncListener { + public: + explicit GuardedListener(SyncListener& inner) : inner(inner) {} + void OnStatus(const AppStatus& s) override { Guard([&] { inner.OnStatus(s); }); } + void OnImported(const Message& m) override { Guard([&] { inner.OnImported(m); }); } + void OnUnstored(const Message& m) override { Guard([&] { inner.OnUnstored(m); }); } + void OnMessageChanged(const Message& m) override { Guard([&] { inner.OnMessageChanged(m); }); } + void OnLog(std::string_view line) override { Guard([&] { inner.OnLog(line); }); } + + private: + template void Guard(F&& call) { + std::string what; + try { + call(); + return; + } catch (const std::exception& e) { + what = e.what(); + } catch (...) { + what = "an exception"; + } + if (telling) return; // the word of the fault threw too: dropped + telling = true; + OnLog(std::format("a listener threw: {}", what)); + telling = false; + } + + SyncListener& inner; + bool telling = false; + }; + + class Sync : public ImsdEvents { + public: + // `countryCode` overrides the code taken from the subscriber's own + // number (imsd's ppi), else from imsd's service centre number ("" for + // none). + Sync(MessageStore& store, ImsdTransport& bus, SyncListener& inner, std::string countryCode = "") + : store(store), bus(bus), listener(inner), countryOverride(std::move(countryCode)) { + known = store.ImsdIds(); + for (const Message& m : store.All()) { + // A message still pending from an earlier run may have had + // imsd's answer while the app was not running: it is failed, + // the user can retry, and an answer that still comes applies + // where the row has imsd's id (one whose Send had no reply + // yet has none: its word is only logged). + if (m.direction == Direction::Outgoing && m.state == MessageState::Pending) store.SetState(m.id, MessageState::Failed, "the app stopped before imsd confirmed it"); + } + // The store's word on its writes: refused — the disk full — texts + // wait (in imsd; one imsd could not store itself, here: Import), + // the banner says so, the 30 s Refresh lists again meanwhile; a + // send still goes, its own write a try, and a write that gets + // room clears it and lists the texts imsd holds at once (the + // Refresh, armed while the store refused, stops with the flag + // once no text is held). The flag is the store's (Refused), read + // here after the sweep above — a refusal during it shows too — + // and again after imsd's vanish resets the status. + store.onWriteState = [this](bool refused, std::string_view why) { + this->listener.OnLog(refused ? std::format("the store refused a write: {} — texts wait until there is room", why) : std::string("the store writes again")); + this->status.storeFailed = refused; + this->listener.OnStatus(this->status); + if (!refused) this->FetchList(); + }; + status.storeFailed = store.Refused(); + if (status.storeFailed) listener.OnStatus(status); + } + + // The store's slot is this Sync's: given back (a later Sync on the + // store takes it next). + ~Sync() override { store.onWriteState = nullptr; } + + const AppStatus& Current() const noexcept { return status; } + + // The conversation on screen: a text for it is stored read and the + // notifier leaves it alone. + void SetOpenConversation(std::optional key) { openConversation = std::move(key); } + + std::string CountryCode() const { + if (!countryOverride.empty()) return countryOverride; + // The own number says which country a national number is in; + // the service centre's only stands in (an MVNO's centre can be + // abroad). + const std::string fromOwn = CountryCodeOf(status.ownNumber); + if (!fromOwn.empty()) return fromOwn; + const std::string fromSmsc = CountryCodeOf(status.smsc); + if (!fromSmsc.empty()) return fromSmsc; + // None known: a national number stays as typed (imsd sends the + // digits with the type unknown, and the network's own plan + // applies). The store's correspondents say nothing about where + // the subscriber is: a code taken from them would send a text to + // another country. + return ""; + } + + // The SIM's plan as known now: the own number's code (--country's + // when given), never the centre's stand-in, and the operator of + // imsd's status. + SimPlan Plan() const { return { !countryOverride.empty() ? countryOverride : CountryCodeOf(status.ownNumber), status.simOperator }; } + + // ---- the bus ------------------------------------------------------- + + void OnImsdAppeared() override { + status.imsdPresent = true; + status.subscribed = false; + Subscribe(); + listener.OnStatus(status); + } + + void OnImsdVanished() override { + status = AppStatus{}; + status.storeFailed = store.Refused(); // the store's state, not imsd's + statusFailed = false; + listFailed = false; + listener.OnStatus(status); + for (const Message& m : store.All()) { + if (m.direction == Direction::Outgoing && m.state == MessageState::Pending) Fail(m.id, "imsd stopped before confirming"); + } + deleting.clear(); + // A copy polkit refused to delete is tried again once imsd is + // back: its count went with the status. + undeletable.clear(); + } + + void OnReceived(const ReceivedMessage& message) override { + Import(message, true); + // The signal may have been the first of several, and a signal + // is queued for nobody: the store is the truth. + FetchList(); + } + + void OnStateChanged(std::string_view id, std::string_view state, std::string_view reason) override { + // imsd's ids are unique across its runs (the run's token): the id + // names one row. + const std::optional row = store.FindByImsdId(id); + if (!row) { + listener.OnLog(std::format("StateChanged for a message not on record: {} {} {}", id, state, reason)); + return; + } + const std::optional word = StateFromImsd(state); + if (!word) { + listener.OnLog(std::format("StateChanged with an unknown state: {} {} {}", id, state, reason)); + return; + } + // imsd gives a message's words in order (its §8.4: the submission's + // `sent` or `failed` first, a status report's only after `sent`), + // so each applies as it comes — after the app's own failures too + // (it stopped before imsd confirmed, imsd stopped): imsd knew. + store.SetState(*row, *word, reason); + Changed(*row); + } + + void OnRegistrationChanged(bool registered) override { + status.registered = registered; + listener.OnStatus(status); + // imsd fills the status it answers with, the service centre's + // number among it, at its registration, and the signal reaches + // every connection: the moment to read it again (on every change: + // an answer on its way may carry the state before the signal), + // and to retry. + if (status.subscribeFailed) Refresh(); + else FetchStatus(); + } + + // ---- the UI -------------------------------------------------------- + + // Tries again the texts held for the store, and what failed since + // imsd appeared: a Subscribe that failed or that polkit refused (its + // answer reads the status and the list), else a failed GetStatus; + // and lists, a failed List among it. + void Refresh() { + RetryHeld(); + if (!status.imsdPresent) return; + if (status.subscribeFailed || (status.subscribeDenied && !status.subscribed)) { + // One at a time: the answer of the Subscribe in flight + // decides, and under a rule that prompts a second one would + // ask over the first one's prompt. + if (subscribing) return; + status.subscribeFailed = false; + Subscribe(); + return; + } + if (statusFailed) FetchStatus(); + FetchList(); + } + + // A Subscribe, a GetStatus or a List failed, or the store refused a + // write, and Refresh would try it again (for the store, by listing); + // or a text is held for the store (Import), which Refresh tries + // again, imsd there or not. A polkit refusal is tried again too: + // imsd asks polkit on every gated call, so one that held while the + // session was inactive lifts when it is active again. + bool RefreshWanted() const noexcept { return !held.empty() || (status.imsdPresent && (status.subscribeFailed || status.subscribeDenied || statusFailed || listFailed || status.storeFailed)); } + + // Stores the message as Pending under its conversation key and + // submits it to `to`, the address as dialled (Number's + // DialledNumber), which the key never stands in for; the row id + // comes back at once, the outcome through OnMessageChanged. + std::uint64_t Send(std::string_view conversation, std::string_view to, std::string_view text) { + Message m; + m.conversation = std::string(conversation); + m.peer = std::string(to); + m.plan = Plan(); // the plan it is dialled under + m.direction = Direction::Outgoing; + m.text = std::string(text); + m.sortTime = NowEpoch(); + m.received = m.sortTime; + m.state = MessageState::Pending; + m.read = true; + const std::optional id = store.Add(m); + if (!id) return kNotStored; // the store refused it: the caller keeps the text + m.id = *id; + listener.OnMessageChanged(m); + Submit(m.id); + return m.id; + } + + // Send's answer when the store refused the row: the text was not + // taken, the caller keeps it (a row id is never this). + static constexpr std::uint64_t kNotStored = ~std::uint64_t{0}; + + // A failed message of ours goes again — without the failed attempt's + // imsd id: a row's imsd id names its current attempt (imsd forgets a + // failed submission's parts, so no word of the old one is due). + void Retry(std::uint64_t id) { + const std::optional m = store.Get(id); + if (!m || m->direction != Direction::Outgoing || m->state != MessageState::Failed) return; + // The row carries the plan it was dialled under; under another + // SIM's it would reach another subscriber or another service + // (Number's AnotherPlan). + if (AnotherPlan(m->peer, m->plan, Plan())) { + Fail(id, "the number was dialled under another SIM's plan: send it again"); + return; + } + // A row's imsd id names its current attempt: the failed one's goes. + store.SetState(id, MessageState::Pending, ""); + store.SetImsdId(id, ""); + Changed(id); + Submit(id); + } + + private: + static std::int64_t NowEpoch() { + return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + } + + void Changed(std::uint64_t id) { + if (const std::optional m = store.Get(id)) listener.OnMessageChanged(*m); + } + + void Fail(std::uint64_t id, std::string_view reason) { + store.SetState(id, MessageState::Failed, reason); + Changed(id); + } + + void Submit(std::uint64_t id) { + if (!CanSend(status)) { + Fail(id, BannerText(status)); + return; + } + const std::optional m = store.Get(id); + if (!m) return; + bus.Send(m->peer, m->text, true, [this, id](SendResult result) { + if (!result) { + Fail(id, result.error().message); + return; + } + // imsd's id names the row for its words: in place, which a + // full disk does not refuse (the row's Add fit). + if (!store.SetImsdId(id, *result)) listener.OnLog(std::format("imsd's id for message {} was not recorded: {}", id, *result)); + Changed(id); + }); + } + + void Subscribe() { + ++subscribing; + bus.Subscribe([this](std::optional err) { + --subscribing; + status.subscribeFailed = false; + if (!err) { + status.subscribed = true; + status.subscribeDenied = false; + } else if (err->kind == BusError::Kind::AccessDenied) { + status.subscribeDenied = true; + listener.OnLog(std::format("Subscribe refused: {}", err->message)); + } else { + status.subscribeFailed = true; + listener.OnLog(std::format("Subscribe failed: {}", err->message)); + } + // The status ends the connecting state and the List brings what + // imsd kept: both at once, since a listed text keys itself by + // the number it arrived for (Model's MessageFromReceived). + FetchStatus(); + FetchList(); + listener.OnStatus(status); + }); + } + + void FetchStatus() { + bus.GetStatus([this](StatusResult result) { + if (!result) { + statusFailed = true; + listener.OnLog(std::format("GetStatus failed: {}", result.error().message)); + listener.OnStatus(status); // RefreshWanted() is true now + } else { + statusFailed = false; + status.statusKnown = true; + status.enabled = result->enabled; + status.registered = result->registered; + status.smsc = result->smsc; + status.ownNumber = result->ownNumber; // from the snapshot smsc came from: a number imsd has is never missing + status.simOperator = result->simOperator; + listener.OnStatus(status); + } + }); + } + + void FetchList() { + if (listInFlight) { + listAgain = true; + return; + } + listInFlight = true; + bus.List([this](ListResult result) { + listInFlight = false; + if (!result) { + // Announced at every failure: the listener's 30 s refresh + // is armed from the status, whenever none runs. A refusal + // is the degraded mode; any other failure (a timeout) + // leaves the texts imsd holds to the next Refresh. + if (result.error().kind == BusError::Kind::AccessDenied) status.subscribeDenied = true; + else listFailed = true; + listener.OnStatus(status); + listener.OnLog(std::format("List failed: {}", result.error().message)); + } else { + listFailed = false; + // A gated call admitted again: the refusal is over (the + // session is active again), and sending with it; and one + // action gates List and Delete, so the copies polkit + // refused to delete can go now — this answer's imports try + // them again, a refusal counted anew. + if ((status.subscribeDenied && status.subscribed) || !undeletable.empty()) { + if (status.subscribed) status.subscribeDenied = false; + undeletable.clear(); + status.undeletable = 0; + listener.OnStatus(status); + } + // A held text this answer carries is imsd's to keep after + // all; the rest of them are tried again below. + for (const ReceivedMessage& r : *result) held.erase(r.imsdId); + for (const ReceivedMessage& r : *result) Import(r); + RetryHeld(); + } + if (listAgain) { + listAgain = false; + FetchList(); + } + }); + } + + // A text from the signal or the list: stored once (imsd's id is the + // key: its run's token makes it unique across imsd's runs, §8.4), + // imsd's copy deleted — again for one still on record, so a copy + // whose delete timed out gets another chance; one polkit refused + // at the next List imsd admits, or once imsd has restarted. A short + // message type 0 (Model's IsType0) is neither stored nor announced: + // imsd acknowledged it, and its copy goes like any other. + // `signalled`: the text came by the Received signal, which imsd + // sends for a text it could not store itself too — the signal is + // then its only delivery, and no List carries the text after. + void Import(const ReceivedMessage& r, bool signalled = false) { + if (!IsType0(r) && !known.contains(r.imsdId)) { + Message m = MessageFromReceived(r); + m.read = openConversation && *openConversation == m.conversation; + const std::optional id = store.Add(m); + if (!id) { + // The store refused the row (its disk full). A listed + // text is imsd's to keep: nothing is deleted, and the + // next List tries again. A signalled one may be nowhere + // else, so it is held here and told once (OnUnstored), + // until a write gets room (RetryHeld) or a List carries + // it; one that is nowhere else is lost with a process + // that ends before then. + if (signalled && held.try_emplace(r.imsdId, r).second) { + m.read = false; + listener.OnUnstored(m); + } + return; + } + held.erase(r.imsdId); + m.id = *id; + known.insert(r.imsdId); + listener.OnImported(m); + } + DeleteStored(r.imsdId); + } + + // The texts held for a store that refused them, tried again: each + // leaves the list when its row is in. + void RetryHeld() { + const std::map waiting = held; + for (const auto& [id, r] : waiting) Import(r, true); + } + + void DeleteStored(const std::string& id) { + if (deleting.contains(id) || undeletable.contains(id)) return; + deleting.insert(id); + bus.Delete(id, [this, id](std::optional err) { + deleting.erase(id); + if (!err || err->kind == BusError::Kind::NotFound) return; + if (err->kind == BusError::Kind::AccessDenied) { + undeletable.insert(id); + status.undeletable = static_cast(undeletable.size()); + listener.OnStatus(status); + } + listener.OnLog(std::format("Delete {} failed: {}", id, err->message)); + }); + } + + MessageStore& store; + ImsdTransport& bus; + GuardedListener listener; // the app's, guarded + std::string countryOverride; + AppStatus status; + bool statusFailed = false; // GetStatus failed since imsd appeared + bool listFailed = false; // List failed, and not by a refusal, since one last succeeded + std::size_t subscribing = 0; // the Subscribes unanswered + std::unordered_set known; // imsd ids in the store + std::map held; // signalled texts the store refused, by imsd id (Import) + std::unordered_set deleting; // Delete calls in flight + std::unordered_set undeletable; // Delete refused by polkit + std::optional openConversation; + bool listInFlight = false; + bool listAgain = false; + }; } diff --git a/project.cpp b/project.cpp index b96a8b7..f5dea32 100644 --- a/project.cpp +++ b/project.cpp @@ -138,6 +138,7 @@ extern "C" Configuration CrafterBuildProject(std::span a cfg.AddTest("Wrap").Dependencies({ Core.get() }); cfg.AddTest("Model").Dependencies({ Core.get() }); cfg.AddTest("Store").Dependencies({ Core.get(), db }); + cfg.AddTest("Sync").Dependencies({ Core.get() }); LintRules::AddRules(cfg); return cfg; diff --git a/tests/Number/main.cpp b/tests/Number/main.cpp index c323fee..ac93ced 100644 --- a/tests/Number/main.cpp +++ b/tests/Number/main.cpp @@ -72,6 +72,26 @@ int main() { CheckEqual(CountryCodeOf("+3912345678"), "39", "two-digit code 39"); CheckEqual(CountryCodeOf("KPN"), "", "no code for an alphanumeric sender"); CheckEqual(CountryCodeOf("0612345678"), "", "no code for a national number"); + const SimPlan kpn{ "31", "20408" }; + const SimPlan vodafoneNl{ "31", "20404" }; + const SimPlan telekomDe{ "49", "26201" }; + Check(AnotherPlan("0612345678", kpn, telekomDe), "AnotherPlan: a national number under another country's SIM"); + Check(AnotherPlan("3477123456", { "39", "22210" }, { "1", "310260" }), "AnotherPlan: a plan without a trunk prefix too"); + Check(AnotherPlan("1234", kpn, telekomDe), "AnotherPlan: a short code too"); + Check(AnotherPlan("0031612345678", kpn, { "1", "310260" }), "AnotherPlan: so is a number behind 00, one plan's international prefix and not another's"); + Check(AnotherPlan("1234", kpn, vodafoneNl), "AnotherPlan: a short code is its operator's: another operator of the same country has another service there"); + Check(!AnotherPlan("0612345678", kpn, vodafoneNl), "AnotherPlan: a national number means the same under another operator of its country"); + Check(!AnotherPlan("612345678", { "34", "21407" }, { "34", "21401" }), "AnotherPlan: one of a plan without a trunk prefix too"); + Check(!AnotherPlan("0031612345678", kpn, vodafoneNl), "AnotherPlan: and one behind the country's international prefix"); + Check(!AnotherPlan("1234", { "", "20408" }, kpn), "AnotherPlan: the same operator is the same plan, a side's code known or not"); + Check(!AnotherPlan("0612345678", kpn, kpn), "AnotherPlan: the same plan"); + Check(!AnotherPlan("+31612345678", kpn, telekomDe), "AnotherPlan: an international address names its own plan"); + Check(AnotherPlan("0612345678", { "", "20408" }, vodafoneNl), "AnotherPlan: under another operator a number written under no known code is not known to mean the same"); + Check(AnotherPlan("0612345678", { "31", "" }, { "49", "" }), "AnotherPlan: without the operators the codes decide alone"); + Check(!AnotherPlan("1234", { "31", "" }, vodafoneNl), "AnotherPlan: an operator missing on one side and the same code, nothing more is known"); + Check(!AnotherPlan("0612345678", {}, telekomDe), "AnotherPlan: written under no known plan, nothing is known"); + Check(!AnotherPlan("0612345678", kpn, {}), "AnotherPlan: no plan known now, nothing is known"); + Check(!AnotherPlan("", kpn, telekomDe), "AnotherPlan: no address"); CheckEqual(NormalizeNumber("+31 (0)6 1234 5678", "31"), "+31612345678", "the parenthesised trunk zero of an international number is dropped"); CheckEqual(NormalizeNumber("+44 (0)20 7946 0018", "31"), "+442079460018", "the same under another country code"); diff --git a/tests/Sync/main.cpp b/tests/Sync/main.cpp new file mode 100644 index 0000000..cf7c0db --- /dev/null +++ b/tests/Sync/main.cpp @@ -0,0 +1,710 @@ +// 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 +#include +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 done; + }; + std::vector subscribes; + std::vector> statuses; + std::vector> lists; + std::vector> deletes; + std::vector sends; + + void Subscribe(Done done) override { subscribes.push_back(std::move(done)); } + void GetStatus(std::function done) override { statuses.push_back(std::move(done)); } + void List(std::function 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 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 err = std::nullopt) { + Done d = std::move(subscribes.front()); + subscribes.erase(subscribes.begin()); + d(err); + } + void AnswerStatus(StatusResult r) { + std::function d = std::move(statuses.front()); + statuses.erase(statuses.begin()); + d(std::move(r)); + } + void AnswerList(ListResult r) { + std::function d = std::move(lists.front()); + lists.erase(lists.begin()); + d(std::move(r)); + } + void AnswerDelete(std::optional err = std::nullopt) { + Done d = std::move(deletes.front().second); + deletes.erase(deletes.begin()); + d(err); + } + void AnswerSend(SendResult r) { + std::function d = std::move(sends.front().done); + sends.erase(sends.begin()); + d(std::move(r)); + } +}; + +struct Recorder : SyncListener { + std::vector statuses; + std::vector imported; + std::vector unstored; + std::vector changed; + std::vector 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(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{ 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{ 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{}); + + // --- 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{}); + Check(bus.lists.size() == 1, "and runs once the first answered"); + bus.AnswerList(std::vector{}); + + // --- 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{ 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{}); + sync.OnReceived(Text("ims-sms-in-1-6", "+31611111111", "later", 1005)); + bus.AnswerDelete(Error(BusError::Kind::Timeout, "timed out")); + bus.AnswerList(std::vector{ 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{}); + 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{}); + 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{}); + 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{}); + 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{ 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{}); + Check(!retrying.RefreshWanted(), "and nothing is wanted once both answered"); + fs::remove_all(retryDir); + } + + // --- 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{ 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{ 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{}); + 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{ 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{ 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{}); + 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); + } + + // --- 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{}); + 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{}); + 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{ 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{ 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); + } + + // --- 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{}); + 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{}); // the signal's List: imsd does not hold the text either + holding.Refresh(); + bus13.AnswerList(std::vector{}); + 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{}); // the recovery's List + bus13.AnswerList(std::vector{}); // 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{ 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{ 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{}); // 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{}); // 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; +}