imsd-messages/interfaces/ImsdMessages-Sync.cppm

528 lines
26 KiB
Text
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
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
/*
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;
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
import :Number;
import :Model;
import :Store;
export namespace ImsdMessages {
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
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<void(std::optional<BusError>)>;
using StatusResult = std::expected<Status, BusError>;
using ListResult = std::expected<std::vector<ReceivedMessage>, BusError>;
using SendResult = std::expected<std::string, BusError>;
// 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<void(StatusResult)> done) = 0;
virtual void List(std::function<void(ListResult)> done) = 0;
virtual void Delete(std::string id, Done done) = 0;
virtual void Send(std::string number, std::string text, bool statusReport, std::function<void(SendResult)> 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 <class F> 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<std::string> 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<std::uint64_t> row = store.FindByImsdId(id);
if (!row) {
listener.OnLog(std::format("StateChanged for a message not on record: {} {} {}", id, state, reason));
return;
}
const std::optional<MessageState> 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<std::uint64_t> 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<Message> 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::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
void Changed(std::uint64_t id) {
if (const std::optional<Message> 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<Message> 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<BusError> 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<std::uint64_t> 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<std::string, ReceivedMessage> 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<BusError> 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<std::uint32_t>(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<std::string> known; // imsd ids in the store
std::map<std::string, ReceivedMessage> held; // signalled texts the store refused, by imsd id (Import)
std::unordered_set<std::string> deleting; // Delete calls in flight
std::unordered_set<std::string> undeletable; // Delete refused by polkit
std::optional<std::string> openConversation;
bool listInFlight = false;
bool listAgain = false;
};
}