main: the resident daemon mode, the send errand and one instance
The executable now runs the app without its window: it owns the session name or forwards to the instance that does (an sms: link, --quit; --quit beside --send is refused, the errand being no instance, and so is a link that is not UTF-8, which D-Bus does not carry; a name request that fails or is refused ends the run with the error's words, exit 1, nobody being shown to run), opens the database (the executable's own Crafter.DB dependency enters here, with its first use), connects the GDBus client to Sync and the notifier, and runs the GLib main loop. --daemon is the resident mode, --headless adds a log line per event for the ssh smoke test on the phone, --session talks to imsd --session, --data-dir and --country override the database directory and the default country code (a country code as the ITU's length rule reads one: a key is made of the code as it is and read by that rule, so anything else is refused). A --daemon with no sms: link that finds the name owned ends at once instead of forwarding an Activate: the running instance already imports and notifies, and a forwarded Activate asks it for its window; --headless then exits 1, having run nothing (a link and --quit are forwarded from a --daemon as from any launch). A Subscribe, a GetStatus or a List that failed against a present imsd is tried again every 30 s, and so is a text Sync holds for a store that refused it; that text is notified all the same (OnUnstored), the notification being where it shows, and is announced as any import once its row is in. --send sends one text to the number as dialled (stored under its normalised key; a NUMBER or TEXT that is not UTF-8 is refused before anything is stored, exit 2: imsd takes D-Bus strings, and GLib would put its own text in the place of other bytes and have that sent; an empty NUMBER is refused there too) and exits on imsd's word for the submission — sent (0) or failed (1), which reaches it as the message's change (a status report's word follows sent, imsd's order) — or on its own failure (1), a store that refuses the text among them; imsd has 60 s to be ready and to take the text, then 2 (no final state) — once it has taken it the clock decides nothing, since imsd bounds its submission itself and ends it with a word, and a clock of the app's would report no final state for a text imsd goes on to send — as a SIGINT or SIGTERM after the start-up, before a final state, is 2 (a resident instance ending on either says so in its log: a session bus closing under it sends SIGTERM too). It is a client of its own: it takes no instance name, since a launch that finds the name taken forwards and exits, and it leaves imsd's stored and signalled texts to the instance that owns the user's store; beside that instance it needs a --data-dir of its own, the store taking one writer. It sends once GetStatus has answered, with Sync's Send gaining a force flag that skips the local readiness check: imsd answers a Send to its caller, subscribed or not, so a refused or unregistered errand ends with imsd's own reason. Its rule is Sync's SendErrand, a class over the listener's events with no GLib in it: one Send once the status is in and none after an end, latched before the call (Sync announces a status from inside Send — the store's word on its write — and the loop can dispatch one after the clock's or a signal's end); one end — the message's final state, the store's refusal, or none on the clock (which decides until imsd has taken the text), a signal or the loop's end; the first of them stands. The shell drives it with its loop, its 60 s source and its log. Tested: tests/Sync, the errand among its cases (a forced send against an unregistered status; imsd's words reaching the listener as the message's changes, as they come), and its rule: one Send across a status announced from inside Send (the store's recovery, end to end on a store refused under the file-size limit), 0 on sent, 1 on failed and on the store's refusal, 2 on the clock before imsd's id and on a signal, the clock deciding nothing once imsd took the text, a final state given first standing over the clock and the loop's end after it.
This commit is contained in:
parent
dcf1aecafd
commit
d9d6f6ef53
4 changed files with 515 additions and 17 deletions
|
|
@ -1,24 +1,302 @@
|
||||||
// SPDX-License-Identifier: GPL-3.0-only
|
// SPDX-License-Identifier: GPL-3.0-only
|
||||||
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
|
||||||
|
|
||||||
|
// lint-disable-file no-char-pointer
|
||||||
/*
|
/*
|
||||||
imsd-messages — the SMS app for imsd's Messaging interface
|
imsd-messages — the SMS app for imsd's Messaging interface
|
||||||
(net.catcrafts.IMS1.Messaging on the system bus). This is the executable:
|
(net.catcrafts.IMS1.Messaging on the system bus).
|
||||||
it parses the command line and wires the bus layer to the window. Nothing
|
|
||||||
runs yet beyond --version.
|
This is the executable. It owns the session-bus name (one instance; a
|
||||||
|
later launch forwards to it), opens the database, connects the GDBus
|
||||||
|
client to the Sync logic and the notifier, and runs the GLib main loop.
|
||||||
|
A --send errand takes no name and imports nothing.
|
||||||
|
Modes:
|
||||||
|
|
||||||
|
imsd-messages the app (the window arrives with the UI milestone)
|
||||||
|
imsd-messages --daemon resident without a window: imports and notifies; beside a running instance it ends at once
|
||||||
|
imsd-messages --headless --daemon with a log line per event (the ssh smoke test)
|
||||||
|
imsd-messages --send N TEXT sends one text; exits once imsd has sent or failed it
|
||||||
|
imsd-messages --quit asks the running instance to exit
|
||||||
|
imsd-messages sms:+316... forwards a conversation to a running instance
|
||||||
|
|
||||||
|
--session talks to `imsd --session` on the session bus; --data-dir and
|
||||||
|
--country override the database directory and the default country code.
|
||||||
*/
|
*/
|
||||||
|
#include <gio/gio.h>
|
||||||
|
#include <glib-unix.h>
|
||||||
|
|
||||||
import std;
|
import std;
|
||||||
|
import Crafter.DB;
|
||||||
import ImsdMessages;
|
import ImsdMessages;
|
||||||
import ImsdMessages.Bus;
|
import ImsdMessages.Bus;
|
||||||
|
using namespace ImsdMessages;
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
struct Options {
|
||||||
|
bool daemon = false;
|
||||||
|
bool headless = false;
|
||||||
|
bool session = false;
|
||||||
|
bool quit = false;
|
||||||
|
bool version = false;
|
||||||
|
bool help = false;
|
||||||
|
std::optional<std::pair<std::string, std::string>> send;
|
||||||
|
std::optional<std::string> uri;
|
||||||
|
std::optional<fs::path> dataDir;
|
||||||
|
std::string country;
|
||||||
|
std::string error;
|
||||||
|
};
|
||||||
|
|
||||||
|
Options Parse(std::span<const char* const> args) {
|
||||||
|
Options o;
|
||||||
|
for (std::size_t i = 0; i < args.size(); ++i) {
|
||||||
|
const std::string_view a = args[i];
|
||||||
|
if (a == "--daemon") o.daemon = true;
|
||||||
|
else if (a == "--headless") o.daemon = o.headless = true;
|
||||||
|
else if (a == "--session") o.session = true;
|
||||||
|
else if (a == "--quit") o.quit = true;
|
||||||
|
else if (a == "--version") o.version = true;
|
||||||
|
else if (a == "--help" || a == "-h") o.help = true;
|
||||||
|
else if (a == "--send" && i + 2 < args.size()) {
|
||||||
|
o.send = std::pair<std::string, std::string>(args[i + 1], args[i + 2]);
|
||||||
|
o.daemon = o.headless = true;
|
||||||
|
i += 2;
|
||||||
|
} else if (a == "--data-dir" && i + 1 < args.size()) o.dataDir = fs::path(args[++i]);
|
||||||
|
else if (a == "--country" && i + 1 < args.size()) o.country = args[++i];
|
||||||
|
else if (a.starts_with("sms:")) o.uri = std::string(a);
|
||||||
|
else o.error = std::format("unknown argument: {}", a);
|
||||||
|
}
|
||||||
|
if (o.send && DialledNumber(o.send->first).empty()) o.error = "--send: NUMBER is empty";
|
||||||
|
// What goes over D-Bus goes as strings, which are UTF-8: GLib would put
|
||||||
|
// its own text in the place of bytes in another encoding — imsd would
|
||||||
|
// send that text, and a forwarded link would name nobody.
|
||||||
|
const auto utf8 = [](const std::string& s) { return g_utf8_validate(s.data(), static_cast<gssize>(s.size()), nullptr) != FALSE; };
|
||||||
|
if (o.send && !(utf8(o.send->first) && utf8(o.send->second))) o.error = "--send: NUMBER and TEXT have to be UTF-8";
|
||||||
|
if (o.uri && !utf8(*o.uri)) o.error = "the sms: link has to be UTF-8";
|
||||||
|
// A country code as the ITU's length rule reads one (none begins with 0,
|
||||||
|
// and CountryCodeOf gives it back from a number that begins with it): a
|
||||||
|
// completed key is made of it as it is, and read by that rule.
|
||||||
|
if (!o.country.empty() && (o.country.front() == '0' || CountryCodeOf(std::format("+{}0000000", o.country)) != o.country)) o.error = "--country: not a country code (one to three digits, without its +)";
|
||||||
|
if (o.send && o.quit) o.error = "--send and --quit do not go together";
|
||||||
|
if (o.send && o.uri) o.error = "--send and an sms: link do not go together";
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Log(std::string_view line) {
|
||||||
|
std::println("imsd-messages: {}", line);
|
||||||
|
std::fflush(stdout);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::path DefaultDataDir() {
|
||||||
|
const gchar* xdg = g_get_user_data_dir();
|
||||||
|
return fs::path(xdg ? xdg : ".") / "imsd-messages";
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the daemon does with Sync's events: log, notify, and run the
|
||||||
|
// --send errand to its end.
|
||||||
|
class Shell : public SyncListener {
|
||||||
|
public:
|
||||||
|
Shell(bool verbose, Bus::Notifier& notifier, GMainLoop* loop) : verbose(verbose), notifier(notifier), loop(loop) {}
|
||||||
|
~Shell() {
|
||||||
|
if (refreshTimer) g_source_remove(refreshTimer);
|
||||||
|
}
|
||||||
|
Shell(const Shell&) = delete;
|
||||||
|
Shell& operator=(const Shell&) = delete;
|
||||||
|
|
||||||
|
Sync* sync = nullptr;
|
||||||
|
std::optional<std::pair<std::string, std::string>> send;
|
||||||
|
SendErrand errand; // the --send errand's rule (Sync's); the loop, the clock and the log are here
|
||||||
|
std::int32_t exitCode = 0;
|
||||||
|
|
||||||
|
void OnStatus(const AppStatus& s) override {
|
||||||
|
if (verbose) {
|
||||||
|
const std::string banner = BannerText(s);
|
||||||
|
Log(std::format("status: imsd {} enabled {} registered {} subscribed {}{}{}", s.imsdPresent ? "up" : "down", s.enabled, s.registered, s.subscribed, s.subscribeDenied ? " (subscribe refused)" : s.subscribeFailed ? " (subscribe failed)" : "", banner.empty() ? "" : std::format(" — {}", banner)));
|
||||||
|
}
|
||||||
|
// What failed against a present imsd is tried again every 30 s.
|
||||||
|
if (sync && sync->RefreshWanted() && !refreshTimer) refreshTimer = g_timeout_add_seconds(30, OnRefresh, this);
|
||||||
|
// The errand sends once GetStatus has answered, which gives the
|
||||||
|
// subscriber's country code for the key (the number itself goes as
|
||||||
|
// dialled), and lets imsd judge the rest: imsd answers a Send to its
|
||||||
|
// caller, subscribed or not, so a refused or unregistered errand
|
||||||
|
// ends with imsd's own reason.
|
||||||
|
if (send && sync && errand.SendDue(s)) End(errand.Sent(sync->Send(NormalizeNumber(send->first, sync->CountryCode()), DialledNumber(send->first), send->second, true)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// A signalled text the store refused: it is in no list and may be in
|
||||||
|
// no store, imsd's included, so the notification is where it shows.
|
||||||
|
void OnUnstored(const Message& m) override {
|
||||||
|
Log(verbose ? std::format("received {} from {}: not stored, held until there is room ({} byte(s))", m.imsdId, m.conversation, m.text.size()) : std::string("a received text could not be stored: held until there is room"));
|
||||||
|
notifier.Notify(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OnImported(const Message& m) override {
|
||||||
|
if (verbose) Log(std::format("received {} from {}: {} ({} byte(s), segments {})", m.imsdId, m.conversation, m.read ? "read" : "unread", m.text.size(), m.segments));
|
||||||
|
if (!m.read) notifier.Notify(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
void OnMessageChanged(const Message& m) override {
|
||||||
|
if (verbose) Log(std::format("message {} ({}): {}{}{}", m.id, m.imsdId.empty() ? "no imsd id yet" : m.imsdId, StateCaption(m.state), m.stateReason.empty() ? "" : " — ", m.stateReason));
|
||||||
|
// The errand's message: imsd's word for the submission ends it — sent
|
||||||
|
// (0), or failed (1); a status report's word follows sent (imsd's
|
||||||
|
// order) — as does the app's own failure (imsd refused the Send, or
|
||||||
|
// stopped), a Failed too.
|
||||||
|
if (send) End(errand.Changed(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
void OnLog(std::string_view line) override { Log(line); }
|
||||||
|
|
||||||
|
// SIGINT or SIGTERM: an errand still waiting reports no final state (2),
|
||||||
|
// not the sent it never saw; a resident instance says why it stops (a
|
||||||
|
// session bus closing under it sends SIGTERM too, GDBus's exit-on-close).
|
||||||
|
void OnSignal() {
|
||||||
|
if (send) End(errand.NoFinalState("interrupted before a final state"));
|
||||||
|
else Log("stopping: SIGINT or SIGTERM");
|
||||||
|
g_main_loop_quit(loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The --send errand's clock, the 60 s source's: for imsd to be ready
|
||||||
|
// and to take the text (SendErrand's TimedOut).
|
||||||
|
void OnTimeout() { End(errand.TimedOut("60 s")); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
// The errand's end, once (the rule's): the exit code, the log line, the
|
||||||
|
// loop's end.
|
||||||
|
void End(std::optional<SendErrand::End> end) {
|
||||||
|
if (!end) return;
|
||||||
|
exitCode = end->code;
|
||||||
|
Log(std::format("--send: {}{}{}", end->caption, end->reason.empty() ? "" : ": ", end->reason));
|
||||||
|
g_main_loop_quit(loop);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every 30 s while a refresh is wanted: the source keeps itself, since a
|
||||||
|
// refresh whose cause stands (the store refusing again, told once) arms
|
||||||
|
// no status; OnStatus arms it only while none runs.
|
||||||
|
static gboolean OnRefresh(gpointer data) {
|
||||||
|
Shell& self = *static_cast<Shell*>(data);
|
||||||
|
if (self.sync && self.sync->RefreshWanted()) {
|
||||||
|
self.sync->Refresh();
|
||||||
|
if (self.sync->RefreshWanted()) return G_SOURCE_CONTINUE;
|
||||||
|
}
|
||||||
|
self.refreshTimer = 0;
|
||||||
|
return G_SOURCE_REMOVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool verbose;
|
||||||
|
Bus::Notifier& notifier;
|
||||||
|
GMainLoop* loop;
|
||||||
|
guint refreshTimer = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
gboolean OnQuitSignal(gpointer data) {
|
||||||
|
static_cast<Shell*>(data)->OnSignal();
|
||||||
|
return G_SOURCE_REMOVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
gboolean OnSendTimeout(gpointer data) {
|
||||||
|
static_cast<Shell*>(data)->OnTimeout();
|
||||||
|
return G_SOURCE_REMOVE;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
int main(int argc, char** argv) {
|
int main(int argc, char** argv) {
|
||||||
for (std::int32_t i = 1; i < argc; ++i) {
|
const Options o = Parse(std::span<const char* const>(argv + 1, static_cast<std::size_t>(argc > 0 ? argc - 1 : 0)));
|
||||||
const std::string_view arg = argv[i];
|
if (!o.error.empty()) {
|
||||||
if (arg == "--version") {
|
Log(o.error);
|
||||||
std::println("imsd-messages {} (glib {})", ImsdMessages::version, ImsdMessages::Bus::glibVersion);
|
return 2;
|
||||||
|
}
|
||||||
|
if (o.version) {
|
||||||
|
std::println("imsd-messages {} (glib {})", version, Bus::glibVersion);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
}
|
if (o.help) {
|
||||||
std::println("imsd-messages {}: nothing to run yet", ImsdMessages::version);
|
std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [sms:NUMBER] [--version]");
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
GError* err = nullptr;
|
||||||
|
GDBusConnection* session = g_bus_get_sync(G_BUS_TYPE_SESSION, nullptr, &err);
|
||||||
|
if (err) {
|
||||||
|
Log(std::format("no session bus ({}): one instance is not enforced and notifications are off", err->message));
|
||||||
|
g_clear_error(&err);
|
||||||
|
}
|
||||||
|
GMainLoop* loop = g_main_loop_new(nullptr, FALSE);
|
||||||
|
Bus::Instance instance(session, {
|
||||||
|
.activate = [] { Log("activated (the window comes with the UI milestone)"); },
|
||||||
|
.open = [](std::vector<std::string> uris) { Log(std::format("open {} (the window comes with the UI milestone)", uris.empty() ? std::string_view("no link") : std::string_view(uris.front()))); },
|
||||||
|
.quit = [loop] { g_main_loop_quit(loop); },
|
||||||
|
});
|
||||||
|
// A send errand is a client of its own: it neither owns the name nor
|
||||||
|
// forwards to the instance that does.
|
||||||
|
const std::optional<Bus::Instance::Owning> owning = session && !o.send ? std::optional(instance.Own()) : std::nullopt;
|
||||||
|
// The name could not be taken, and nobody is shown to hold it: this
|
||||||
|
// process cannot be the instance and knows of none. It says so and
|
||||||
|
// fails, whatever it was asked for.
|
||||||
|
if (owning == Bus::Instance::Owning::Failed) {
|
||||||
|
Log(std::format("could not take the name {} on the session bus: {}", Bus::appId, instance.Failure()));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (owning == Bus::Instance::Owning::Taken) {
|
||||||
|
if (o.quit) return Bus::Instance::ForwardQuit(session) ? 0 : 1;
|
||||||
|
// A second --daemon (a login entry beside the running instance) has
|
||||||
|
// nothing to add, and a forwarded Activate would ask for the window;
|
||||||
|
// the smoke test says it ran nothing.
|
||||||
|
if (o.daemon && !o.uri) {
|
||||||
|
Log(o.headless ? "already running: the smoke test ran nothing" : "already running");
|
||||||
|
return o.headless ? 1 : 0;
|
||||||
|
}
|
||||||
|
const bool forwarded = o.uri ? Bus::Instance::ForwardOpen(session, *o.uri) : Bus::Instance::ForwardActivate(session);
|
||||||
|
Log(forwarded ? "already running: forwarded" : "another instance owns the name but did not answer");
|
||||||
|
return forwarded ? 0 : 1;
|
||||||
|
}
|
||||||
|
if (o.quit) {
|
||||||
|
Log("not running");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fs::path dataDir = o.dataDir.value_or(DefaultDataDir());
|
||||||
|
std::optional<MessageStore> store;
|
||||||
|
try {
|
||||||
|
store.emplace(dataDir);
|
||||||
|
} catch (const Crafter::DB::LockedError& e) {
|
||||||
|
Log(std::format("another imsd-messages holds {}: {}", dataDir.string(), e.what()));
|
||||||
|
return 1;
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
Log(std::format("cannot open the database in {}: {}", dataDir.string(), e.what()));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
GDBusConnection* bus = g_bus_get_sync(o.session ? G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM, nullptr, &err);
|
||||||
|
if (err) {
|
||||||
|
Log(std::format("no {} bus: {}", o.session ? "session" : "system", err->message));
|
||||||
|
g_clear_error(&err);
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bus::Notifier notifier(session);
|
||||||
|
notifier.onOpen = [](const std::string& conversation) { Log(std::format("notification tapped for {} (the window comes with the UI milestone)", conversation)); };
|
||||||
|
if (o.headless) notifier.onLog = Log;
|
||||||
|
Shell shell(o.headless, notifier, loop);
|
||||||
|
shell.send = o.send;
|
||||||
|
Bus::ImsdClient client(bus);
|
||||||
|
Sync sync(*store, client, shell, o.country);
|
||||||
|
// The errand runs beside the instance that owns the user's store (with
|
||||||
|
// a --data-dir of its own): imsd's texts are that instance's to import.
|
||||||
|
if (o.send) sync.LeaveTexts();
|
||||||
|
shell.sync = &sync;
|
||||||
|
Log(std::format("{} {}; database {}; imsd on the {} bus; notifications {}", version, o.send ? "sending one text" : o.daemon ? "resident" : "starting", dataDir.string(), o.session ? "session" : "system", notifier.Enabled() ? "on" : "off"));
|
||||||
|
client.Start(sync);
|
||||||
|
|
||||||
|
g_unix_signal_add(SIGINT, OnQuitSignal, &shell);
|
||||||
|
g_unix_signal_add(SIGTERM, OnQuitSignal, &shell);
|
||||||
|
if (o.send) g_timeout_add_seconds(60, OnSendTimeout, &shell);
|
||||||
|
g_main_loop_run(loop);
|
||||||
|
|
||||||
|
client.Stop();
|
||||||
|
store->Flush();
|
||||||
|
if (session) g_dbus_connection_flush_sync(session, nullptr, nullptr); // a forwarded quit's reply, still queued, goes out before the exit
|
||||||
|
g_main_loop_unref(loop);
|
||||||
|
return shell.exitCode;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,8 @@ logic over an abstract transport.
|
||||||
|
|
||||||
imsd keeps a received text it could store until the app deletes it: the
|
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
|
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
|
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
|
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
|
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
|
is a StateChanged for that id. All of it runs on one thread (the GLib main
|
||||||
|
|
@ -169,6 +170,11 @@ export namespace ImsdMessages {
|
||||||
// notifier leaves it alone.
|
// notifier leaves it alone.
|
||||||
void SetOpenConversation(std::optional<std::string> key) { openConversation = std::move(key); }
|
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 {
|
std::string CountryCode() const {
|
||||||
if (!countryOverride.empty()) return countryOverride;
|
if (!countryOverride.empty()) return countryOverride;
|
||||||
// The own number says which country a national number is in;
|
// The own number says which country a national number is in;
|
||||||
|
|
@ -288,8 +294,9 @@ export namespace ImsdMessages {
|
||||||
// Stores the message as Pending under its conversation key and
|
// Stores the message as Pending under its conversation key and
|
||||||
// submits it to `to`, the address as dialled (Number's
|
// submits it to `to`, the address as dialled (Number's
|
||||||
// DialledNumber), which the key never stands in for; the row id
|
// DialledNumber), which the key never stands in for; the row id
|
||||||
// comes back at once, the outcome through OnMessageChanged.
|
// comes back at once, the outcome through OnMessageChanged. `force`
|
||||||
std::uint64_t Send(std::string_view conversation, std::string_view to, std::string_view text) {
|
// 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;
|
Message m;
|
||||||
m.conversation = std::string(conversation);
|
m.conversation = std::string(conversation);
|
||||||
m.peer = std::string(to);
|
m.peer = std::string(to);
|
||||||
|
|
@ -304,7 +311,7 @@ export namespace ImsdMessages {
|
||||||
if (!id) return kNotStored; // the store refused it: the caller keeps the text
|
if (!id) return kNotStored; // the store refused it: the caller keeps the text
|
||||||
m.id = *id;
|
m.id = *id;
|
||||||
listener.OnMessageChanged(m);
|
listener.OnMessageChanged(m);
|
||||||
Submit(m.id);
|
Submit(m.id, force);
|
||||||
return m.id;
|
return m.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -346,8 +353,8 @@ export namespace ImsdMessages {
|
||||||
Changed(id);
|
Changed(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Submit(std::uint64_t id) {
|
void Submit(std::uint64_t id, bool force = false) {
|
||||||
if (!CanSend(status)) {
|
if (!force && !CanSend(status)) {
|
||||||
Fail(id, BannerText(status));
|
Fail(id, BannerText(status));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -409,6 +416,7 @@ export namespace ImsdMessages {
|
||||||
}
|
}
|
||||||
|
|
||||||
void FetchList() {
|
void FetchList() {
|
||||||
|
if (leaveTexts) return;
|
||||||
if (listInFlight) {
|
if (listInFlight) {
|
||||||
listAgain = true;
|
listAgain = true;
|
||||||
return;
|
return;
|
||||||
|
|
@ -462,6 +470,7 @@ export namespace ImsdMessages {
|
||||||
// sends for a text it could not store itself too — the signal is
|
// sends for a text it could not store itself too — the signal is
|
||||||
// then its only delivery, and no List carries the text after.
|
// then its only delivery, and no List carries the text after.
|
||||||
void Import(const ReceivedMessage& r, bool signalled = false) {
|
void Import(const ReceivedMessage& r, bool signalled = false) {
|
||||||
|
if (leaveTexts) return;
|
||||||
if (!IsType0(r) && !known.contains(r.imsdId)) {
|
if (!IsType0(r) && !known.contains(r.imsdId)) {
|
||||||
Message m = MessageFromReceived(r);
|
Message m = MessageFromReceived(r);
|
||||||
m.read = openConversation && *openConversation == m.conversation;
|
m.read = openConversation && *openConversation == m.conversation;
|
||||||
|
|
@ -527,5 +536,77 @@ export namespace ImsdMessages {
|
||||||
std::optional<std::string> openConversation;
|
std::optional<std::string> openConversation;
|
||||||
bool listInFlight = false;
|
bool listInFlight = false;
|
||||||
bool listAgain = 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;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -134,7 +134,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
|
||||||
cfg.outputName = "imsd-messages";
|
cfg.outputName = "imsd-messages";
|
||||||
ApplyStandardArgs(cfg, args);
|
ApplyStandardArgs(cfg, args);
|
||||||
cfg.type = ConfigurationType::Executable;
|
cfg.type = ConfigurationType::Executable;
|
||||||
cfg.dependencies = { Core.get(), Bus.get() };
|
cfg.dependencies = { Core.get(), Bus.get(), db };
|
||||||
{
|
{
|
||||||
std::array<fs::path, 0> ifaces = {};
|
std::array<fs::path, 0> ifaces = {};
|
||||||
std::array<fs::path, 1> impls = { "implementations/main" };
|
std::array<fs::path, 1> impls = { "implementations/main" };
|
||||||
|
|
|
||||||
|
|
@ -589,6 +589,43 @@ int main() {
|
||||||
fs::remove_all(throwDir);
|
fs::remove_all(throwDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- the --send errand: it sends, and leaves imsd's texts to the instance --------------
|
||||||
|
{
|
||||||
|
const fs::path errandDir = fs::temp_directory_path() / "imsd-messages-sync-errand";
|
||||||
|
fs::remove_all(errandDir);
|
||||||
|
MessageStore errandStore(errandDir);
|
||||||
|
Fake bus3;
|
||||||
|
Recorder events3;
|
||||||
|
Sync errand(errandStore, bus3, events3, "31");
|
||||||
|
errand.LeaveTexts();
|
||||||
|
errand.OnImsdAppeared();
|
||||||
|
bus3.AnswerSubscribe();
|
||||||
|
Check(bus3.statuses.size() == 1 && bus3.lists.empty(), "the errand asks for the status and lists nothing");
|
||||||
|
bus3.AnswerStatus(Online());
|
||||||
|
errand.OnReceived(Text("ims-sms-in-9-1", "+31621308050", "for the instance", 1100));
|
||||||
|
Check(errandStore.Size() == 0 && bus3.deletes.empty() && bus3.lists.empty(), "a signalled text is neither imported nor deleted by the errand");
|
||||||
|
const std::uint64_t sent = errand.Send("+31621308050", "+31621308050", "from the errand", true);
|
||||||
|
Check(bus3.sends.size() == 1 && bus3.sends[0].text == "from the errand", "the errand sends");
|
||||||
|
bus3.AnswerSend(std::string("ims-sms-9"));
|
||||||
|
// imsd's words reach the listener as the message's changes, as they
|
||||||
|
// come, the submission's first (imsd's order); the errand ends on it.
|
||||||
|
errand.OnStateChanged("ims-sms-9", "sent", "");
|
||||||
|
errand.OnStateChanged("ims-sms-9", "delivery-pending", "TP-ST 0x30");
|
||||||
|
std::vector<MessageState> seen; // the message's states as announced (the pending's announcements — the Send's, the id's — collapsed)
|
||||||
|
for (const Message& m : events3.changed) if (m.id == sent) seen.push_back(m.state);
|
||||||
|
seen.erase(std::unique(seen.begin(), seen.end()), seen.end());
|
||||||
|
Check(seen == std::vector<MessageState>{ MessageState::Pending, MessageState::Sent, MessageState::DeliveryPending } && errandStore.Get(sent)->state == MessageState::DeliveryPending, "imsd's words reach the listener as the message's changes, as they come, and the store follows them");
|
||||||
|
// Unregistered: a send fails at once, a forced one goes to imsd.
|
||||||
|
errand.OnRegistrationChanged(false);
|
||||||
|
const std::uint64_t local = errand.Send("+31621308050", "+31621308050", "not forced");
|
||||||
|
Check(errandStore.Get(local)->state == MessageState::Failed && bus3.sends.empty(), "unregistered, a send fails without asking imsd");
|
||||||
|
const std::uint64_t forced = errand.Send("+31621308050", "+31621308050", "forced", true);
|
||||||
|
Check(bus3.sends.size() == 1 && bus3.sends[0].text == "forced", "a forced send goes to imsd all the same");
|
||||||
|
bus3.AnswerSend(std::unexpected(Error(BusError::Kind::Other, "imsd is not registered")));
|
||||||
|
Check(errandStore.Get(forced)->state == MessageState::Failed && errandStore.Get(forced)->stateReason == "imsd is not registered", "and fails with imsd's reason");
|
||||||
|
fs::remove_all(errandDir);
|
||||||
|
}
|
||||||
|
|
||||||
// --- the store refusing a write: the file-size limit stands in for a full disk ------------
|
// --- 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";
|
const fs::path fullDir = fs::temp_directory_path() / "imsd-messages-sync-full";
|
||||||
|
|
@ -648,6 +685,108 @@ int main() {
|
||||||
fs::remove_all(fullDir);
|
fs::remove_all(fullDir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- the --send errand's rule (Sync's SendErrand): one Send, one end -----------------
|
||||||
|
{
|
||||||
|
SendErrand e;
|
||||||
|
AppStatus s;
|
||||||
|
Check(!e.SendDue(s), "no Send before imsd is there");
|
||||||
|
s.imsdPresent = true;
|
||||||
|
Check(!e.SendDue(s), "nor before its status is in");
|
||||||
|
s.statusKnown = true;
|
||||||
|
Check(e.SendDue(s) && !e.SendDue(s), "once the status is in: one Send; a second status — one announced from inside Send — makes none");
|
||||||
|
Check(!e.Sent(7).has_value(), "a stored row is followed, nothing ends");
|
||||||
|
Message other;
|
||||||
|
other.id = 8;
|
||||||
|
other.state = MessageState::Sent;
|
||||||
|
Check(!e.Changed(other).has_value(), "another message's final state is not the errand's");
|
||||||
|
Message own;
|
||||||
|
own.id = 7;
|
||||||
|
own.state = MessageState::Pending;
|
||||||
|
Check(!e.Changed(own).has_value(), "a pending change ends nothing");
|
||||||
|
own.state = MessageState::Sent;
|
||||||
|
own.stateReason = "2026-11-01T22:00:00+01:00";
|
||||||
|
const std::optional<SendErrand::End> sent = e.Changed(own);
|
||||||
|
Check(sent && sent->code == 0 && sent->caption == "Sent" && sent->reason == "2026-11-01T22:00:00+01:00" && e.Done(), "sent: 0, imsd's caption and reason");
|
||||||
|
Check(!e.TimedOut("60 s").has_value() && !e.NoFinalState("ended before a final state").has_value(), "a final state given first stands: the clock and the loop's end after it change nothing");
|
||||||
|
own.state = MessageState::Failed;
|
||||||
|
Check(!e.Changed(own).has_value(), "and over a later word");
|
||||||
|
SendErrand failing;
|
||||||
|
failing.SendDue(s);
|
||||||
|
failing.Sent(9);
|
||||||
|
Message f;
|
||||||
|
f.id = 9;
|
||||||
|
f.state = MessageState::Failed;
|
||||||
|
f.stateReason = "RP-ERROR cause 38";
|
||||||
|
const std::optional<SendErrand::End> fe = failing.Changed(f);
|
||||||
|
Check(fe && fe->code == 1 && fe->caption == "Failed" && fe->reason == "RP-ERROR cause 38", "failed: 1, with imsd's reason");
|
||||||
|
SendErrand refused;
|
||||||
|
refused.SendDue(s);
|
||||||
|
const std::optional<SendErrand::End> re = refused.Sent(Sync::kNotStored);
|
||||||
|
Check(re && re->code == 1 && re->caption == "Failed" && re->reason == "the store did not take the text" && refused.Done(), "a store that refused the text: 1, ended");
|
||||||
|
SendErrand early;
|
||||||
|
const std::optional<SendErrand::End> te = early.TimedOut("60 s");
|
||||||
|
Check(te && te->code == 2 && te->caption == "imsd did not become ready within 60 s", "the clock before the status: 2, imsd not ready");
|
||||||
|
Check(!early.SendDue(s), "and no Send after it: a status dispatched after the clock's end makes none");
|
||||||
|
SendErrand waiting;
|
||||||
|
waiting.SendDue(s);
|
||||||
|
waiting.Sent(3);
|
||||||
|
const std::optional<SendErrand::End> tw = waiting.TimedOut("60 s");
|
||||||
|
Check(tw && tw->code == 2 && tw->caption == "no final state within 60 s" && !waiting.TimedOut("60 s").has_value(), "the clock after the Send, before imsd's id: 2, no final state — once");
|
||||||
|
SendErrand taken;
|
||||||
|
taken.SendDue(s);
|
||||||
|
taken.Sent(5);
|
||||||
|
Message t;
|
||||||
|
t.id = 5;
|
||||||
|
t.state = MessageState::Pending;
|
||||||
|
t.imsdId = "ims-sms-5";
|
||||||
|
Check(!taken.Changed(t).has_value() && !taken.TimedOut("60 s").has_value() && !taken.Done(), "the clock once imsd has taken the text decides nothing: imsd bounds its submission itself");
|
||||||
|
t.state = MessageState::Sent;
|
||||||
|
const std::optional<SendErrand::End> ts = taken.Changed(t);
|
||||||
|
Check(ts && ts->code == 0 && taken.Done(), "and imsd's word ends the errand, however long after");
|
||||||
|
SendErrand signalled;
|
||||||
|
signalled.SendDue(s);
|
||||||
|
signalled.Sent(4);
|
||||||
|
const std::optional<SendErrand::End> si = signalled.NoFinalState("interrupted before a final state");
|
||||||
|
Check(si && si->code == 2 && si->caption == "interrupted before a final state", "a signal: 2");
|
||||||
|
SendErrand ended;
|
||||||
|
ended.NoFinalState("interrupted before a final state");
|
||||||
|
Check(!ended.SendDue(s), "nor a Send after a signal's end before any");
|
||||||
|
}
|
||||||
|
// The rule end to end, in the shape that sent two texts once: a listener
|
||||||
|
// running it from OnStatus, over a store refused before and recovering
|
||||||
|
// inside the Send's own write — which announces a status from inside
|
||||||
|
// Send. One text to imsd.
|
||||||
|
{
|
||||||
|
struct ErrandListener : Recorder {
|
||||||
|
Sync* sync = nullptr;
|
||||||
|
SendErrand errand;
|
||||||
|
std::size_t sends = 0;
|
||||||
|
void OnStatus(const AppStatus& s) override {
|
||||||
|
Recorder::OnStatus(s);
|
||||||
|
if (sync && errand.SendDue(s)) {
|
||||||
|
++sends;
|
||||||
|
errand.Sent(sync->Send("+31621308050", "+31621308050", std::string(4096, 'z'), true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const fs::path reDir = fs::temp_directory_path() / "imsd-messages-sync-reentry";
|
||||||
|
fs::remove_all(reDir);
|
||||||
|
MessageStore reStore(reDir);
|
||||||
|
Fake bus10;
|
||||||
|
ErrandListener events10;
|
||||||
|
Sync reSync(reStore, bus10, events10, "31");
|
||||||
|
events10.sync = &reSync;
|
||||||
|
reSync.LeaveTexts();
|
||||||
|
const rlimit before = FillUntilRefused(reStore, reDir);
|
||||||
|
Check(reStore.Refused(), "the store refused a write");
|
||||||
|
setrlimit(RLIMIT_FSIZE, &before); // room again: the errand's own write will grow the file and tell of the recovery, from inside Send
|
||||||
|
reSync.OnImsdAppeared();
|
||||||
|
bus10.AnswerSubscribe();
|
||||||
|
bus10.AnswerStatus(Online());
|
||||||
|
Check(events10.sends == 1 && bus10.sends.size() == 1 && !reStore.Refused() && !events10.errand.Done(), "the status announced from inside the errand's Send makes no second Send: one text to imsd");
|
||||||
|
fs::remove_all(reDir);
|
||||||
|
}
|
||||||
|
|
||||||
// --- a signalled text the store refuses: imsd signals a text it could not
|
// --- 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
|
// store itself too, so no List may ever carry it — held, told, stored
|
||||||
// when there is room ---------------------------------------------------
|
// when there is room ---------------------------------------------------
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue