imsd keeps a received text until an app deletes it, and a delete can be refused (polkit, for a session that is not the active one) or time out: the List after the next start would carry the text again and the app would import it again (within a run Sync's own record of what it imported keeps it out). And a deleted row is a tombstone whose bytes stay in the file until it is rewritten. The store gains a second table, erased.cdb: the imsd ids of received texts the user deleted while imsd may still hold their copies, its format held by the build as the first table's is. Erase and EraseConversation remember the id before the row goes (a crash between the two leaves a remembered id, never a text that comes back; a remembering the store refuses refuses the delete), ImsdIds folds the remembered ids in, so Sync's `known` keeps a List from importing them, and ForgetErased drops the ids a List no longer carries — of those remembered before that List was sent: an id remembered while it was in flight waits for the next (FetchList's `before` snapshot). Sync's Erase and EraseConversation go to the store; Fail and the Send continuation check that the row still exists, so a text deleted while its Send is in flight takes no late word, and a late answer for a deleted message finds no row and is logged. main compacts both files at start when either holds deleted rows or bytes an update or a delete orphaned (a state reason replaced by another can leave some, so a start after a send may rewrite both with nothing deleted), and opens the store again on what is there if the rewrite failed: a deleted text's bytes leave the files at the next start (a resident instance keeps them until then — nothing holds a row id across the rewrite but the app itself). Tested: tests/Store — the remembered ids across a reopen and as known, a deleted sent text's id not remembered, the ids imsd no longer lists forgotten, the bytes of deleted texts and forgotten ids gone after the Compact and a reopen while the kept ones stay, a forgotten id alone enough for a Compact, the second file private and rewritten with the first; tests/Sync — a message deleted while it is sending (its late answers write nothing and are logged), a received text imported, remembered when deleted and forgotten when no longer listed, a text signalled while a List is in flight kept by the List sent before the delete — which forgets the id remembered before it went out — and forgotten by the next, and a state for another client's text leaving every message alone.
632 lines
31 KiB
C++
632 lines
31 KiB
C++
// 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 --send errand leaves that to the instance that
|
|
owns the user's store. 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<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;
|
|
virtual void OnFault(std::string_view what) {} // a callback threw (a read, an allocation; the store catches its writes): logged, not fatal
|
|
};
|
|
|
|
// 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); }
|
|
|
|
// The --send errand: it sends and follows its own message and
|
|
// leaves the texts imsd keeps to the instance that owns the user's
|
|
// store, so it lists, imports and deletes nothing.
|
|
void LeaveTexts() { leaveTexts = true; }
|
|
|
|
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. `force`
|
|
// skips the local readiness check and lets imsd answer.
|
|
std::uint64_t Send(std::string_view conversation, std::string_view to, std::string_view text, bool force = false) {
|
|
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, force);
|
|
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};
|
|
|
|
// The user's deletes: the rows go. What imsd answers later for a
|
|
// deleted message finds no row and is logged.
|
|
void Erase(std::uint64_t id) { store.Erase(id); }
|
|
|
|
void EraseConversation(std::string_view conversation) { store.EraseConversation(conversation); }
|
|
|
|
// 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) {
|
|
if (!store.Get(id)) {
|
|
listener.OnLog(std::format("message {} failed after it was deleted: {}", id, reason));
|
|
return;
|
|
}
|
|
store.SetState(id, MessageState::Failed, reason);
|
|
Changed(id);
|
|
}
|
|
|
|
void Submit(std::uint64_t id, bool force = false) {
|
|
if (!force && !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;
|
|
}
|
|
if (!store.Get(id)) {
|
|
listener.OnLog(std::format("imsd took message {} as {} after it was deleted", id, *result));
|
|
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 (leaveTexts) return;
|
|
if (listInFlight) {
|
|
listAgain = true;
|
|
return;
|
|
}
|
|
listInFlight = true;
|
|
bus.List([this, before = store.ErasedImsdIds()](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);
|
|
}
|
|
std::unordered_set<std::string> listed;
|
|
for (const ReceivedMessage& r : *result) listed.insert(r.imsdId);
|
|
// 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();
|
|
// A deleted text imsd no longer holds needs no memory — among
|
|
// those remembered before this List went out: one deleted
|
|
// while it was in flight is a text this answer predates.
|
|
store.ForgetErased(listed, before);
|
|
}
|
|
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 (leaveTexts) return;
|
|
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 OnFault(std::string_view what) override { listener.OnLog(std::format("a bus callback failed: {}", what)); }
|
|
|
|
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;
|
|
bool leaveTexts = false;
|
|
};
|
|
|
|
// The --send errand's rule over Sync's events: one Send once imsd's
|
|
// status is in — latched before the call, since Sync announces a
|
|
// status from inside Send (the store's word on its write) — and one
|
|
// end: the message's final state (Sent 0, Failed 1), a store that
|
|
// refused the text (1), or none — the clock, a signal, the loop's end —
|
|
// (2). The clock is for getting the text to imsd: once imsd has taken
|
|
// it, its word ends the errand. The loop, the clock and the log are the
|
|
// shell's (main).
|
|
class SendErrand {
|
|
public:
|
|
struct End {
|
|
std::int32_t code;
|
|
std::string caption; // the log's: the state's, or what ended the errand without one
|
|
std::string reason;
|
|
};
|
|
|
|
// The Send is due on this status: once, only with imsd's status in,
|
|
// and never after an end (the loop can dispatch a status after the
|
|
// clock's or a signal's end).
|
|
bool SendDue(const AppStatus& s) {
|
|
if (started || done || !s.imsdPresent || !s.statusKnown) return false;
|
|
started = true;
|
|
return true;
|
|
}
|
|
|
|
// Send's answer: the row to follow, or kNotStored, which ends the errand.
|
|
std::optional<End> Sent(std::uint64_t id) {
|
|
if (id == Sync::kNotStored) return Ended(1, "Failed", "the store did not take the text");
|
|
sentId = id;
|
|
return std::nullopt;
|
|
}
|
|
|
|
// A message's change: the errand's own, in a final state, ends it;
|
|
// with imsd's id on it, imsd has taken the text.
|
|
std::optional<End> Changed(const Message& m) {
|
|
if (!sentId || m.id != *sentId) return std::nullopt;
|
|
if (!m.imsdId.empty()) taken = true;
|
|
if (m.state == MessageState::Sent) return Ended(0, std::string(StateCaption(m.state)), m.stateReason);
|
|
if (m.state == MessageState::Failed) return Ended(1, std::string(StateCaption(m.state)), m.stateReason);
|
|
return std::nullopt;
|
|
}
|
|
|
|
// The clock ran out (`after`: the shell's span) before imsd was ready
|
|
// or had taken the text. Once it has, the clock decides nothing:
|
|
// imsd bounds a submission itself, segment by segment, and ends it
|
|
// with a word — a clock of the app's own would report no final state
|
|
// for a text imsd goes on to send, and leave its row to fail at the
|
|
// next start.
|
|
std::optional<End> TimedOut(std::string_view after) {
|
|
if (taken) return std::nullopt;
|
|
return Ended(2, started ? std::format("no final state within {}", after) : std::format("imsd did not become ready within {}", after), "");
|
|
}
|
|
|
|
// A signal, or the loop ended by something else: no final state.
|
|
std::optional<End> NoFinalState(std::string_view how) { return Ended(2, std::string(how), ""); }
|
|
|
|
bool Done() const noexcept { return done; }
|
|
|
|
private:
|
|
std::optional<End> Ended(std::int32_t code, std::string caption, std::string reason) {
|
|
if (done) return std::nullopt;
|
|
done = true;
|
|
return End{ code, std::move(caption), std::move(reason) };
|
|
}
|
|
|
|
bool started = false; // the Send was made
|
|
bool taken = false; // imsd answered it with an id
|
|
bool done = false; // the end was given
|
|
std::optional<std::uint64_t> sentId;
|
|
};
|
|
}
|