diff --git a/implementations/main.cpp b/implementations/main.cpp index 4a36e12..6ab17d9 100644 --- a/implementations/main.cpp +++ b/implementations/main.cpp @@ -349,6 +349,25 @@ int main(int argc, char** argv) { Log(std::format("cannot open the database in {}: {}", dataDir.string(), e.what())); return 1; } + // A deleted text is a tombstoned row whose bytes stay in the file until + // it is rewritten; nothing holds a row id yet, so the rewrite is here. A + // resident instance keeps a deleted text's bytes until its next start. + if (store->HasDeleted()) { + try { + store->Compact(); + } catch (const std::exception& e) { + // A rewrite that failed may have renamed its file over the old + // one already: the store is opened again on what is there. + Log(std::format("the database in {} was not compacted: {}", dataDir.string(), e.what())); + store.reset(); + try { + store.emplace(dataDir); + } catch (const std::exception& again) { + Log(std::format("cannot open the database in {} after the failed compaction: {}", dataDir.string(), again.what())); + return 1; + } + } + } GDBusConnection* bus = g_bus_get_sync(o.session ? G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM, nullptr, &err); if (err) { diff --git a/interfaces/ImsdMessages-Store.cppm b/interfaces/ImsdMessages-Store.cppm index 96db99b..90742d8 100644 --- a/interfaces/ImsdMessages-Store.cppm +++ b/interfaces/ImsdMessages-Store.cppm @@ -2,15 +2,17 @@ // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® /* -ImsdMessages:Store — the app's message database, one Crafter.DB table. +ImsdMessages:Store — the app's message database: a Crafter.DB table of +the messages (messages.cdb) and one of the imsd ids of received texts the +user deleted while imsd may still hold their copies (erased.cdb). The table has no ordered column on purpose: Crafter.DB enforces the order on every write, and a List() import after a restart can carry an older stamp than the last row. SMS volumes make a scan free, so conversations are derived from a scan (ImsdMessages:Model) and a conversation's messages are -sorted here. One Table per file: a second MessageStore on the same +sorted here. One MessageStore per directory: a second one on the same directory, in this process or another, throws Crafter::DB::LockedError — -on a lock file beside the table, held for the store's life, since the +on a lock file beside the tables, held for the store's life, since a table's own lock moves with the file a Compact replaces. Every change a call answers as made is flushed before the call returns: @@ -70,6 +72,19 @@ namespace ImsdMessages { inline constexpr Crafter::DB::Column<&MessageRow::imsdId> imsdIdColumn{}; + // A received text the user deleted while imsd may still hold its copy + // (a delete it refused or that timed out): its imsd id, so a later List + // does not import it; dropped once imsd no longer lists it. + struct ErasedRow { + ImsdId imsdId; + + static constexpr std::uint32_t version = 1; + }; + + // Held by the build as MessageRow's format is. + static_assert(Crafter::DB::Layout::rowSize == 65); + static_assert(Crafter::DB::Layout::fingerprint == 0xad3324d2c7d75ee0); + // One MessageStore per directory, held for its life on a file nothing // renames: the table's own lock sits on its file's inode, which a // Compact replaces (a new file renamed over the old), so a second opener @@ -154,8 +169,8 @@ namespace ImsdMessages { export namespace ImsdMessages { class MessageStore { public: - // Opens or creates /messages.cdb (a directory it creates 0700, - // the file 0600). Throws Crafter::DB::LockedError when another + // Opens or creates /messages.cdb and erased.cdb (a directory it + // creates 0700, the files 0600). Throws Crafter::DB::LockedError when another // MessageStore holds it. Every write but a Compact is caught here: one the // store refuses (Crafter.DB's IOError — the disk full, the file system // read-only) answers nullopt (Add), false or 0 (a count) — a row Add @@ -169,7 +184,7 @@ export namespace ImsdMessages { // rewrites a written page in place (ext4, f2fs: the phone's); a // copy-on-write one (btrfs) can refuse the rewrite of a mapped page // with SIGBUS, which no gate sees — Crafter.DB maps its files. - explicit MessageStore(const std::filesystem::path& dir) : lock(dir), table(dir / "messages.cdb") {} + explicit MessageStore(const std::filesystem::path& dir) : lock(dir), table(dir / "messages.cdb"), erased(dir / "erased.cdb") {} std::function onWriteState; @@ -245,23 +260,72 @@ export namespace ImsdMessages { } bool Erase(std::uint64_t id) { - bool erased = false; + // The id first, the row after: a crash between the two leaves a + // remembered id, never a text that comes back — and a remembering + // the store refuses refuses the delete. + if (const std::optional m = Get(id); m && m->direction == Direction::Incoming && !m->imsdId.empty() && !RememberErased(m->imsdId)) return false; + bool gone = false; if (!Write([&] { - erased = table.Erase(id); - if (erased) table.Flush(); + gone = table.Erase(id); + if (gone) table.Flush(); })) return false; - return erased; + return gone; } std::uint64_t EraseConversation(std::string_view conversation) { - std::uint64_t erased = 0; - if (!Write([&] { - erased = table.EraseIf([&](Crafter::DB::Row row) { return row[&MessageRow::conversation] == conversation; }); - if (erased > 0) table.Flush(); + // The ids first, the rows after, as Erase does: a crash between + // the two leaves a remembered id, never a text that comes back. + // One append and one flush for all of them. + std::vector remembered; + for (Crafter::DB::Row row : table) { + if (row[&MessageRow::conversation] != conversation) continue; + const ImsdId id = row[&MessageRow::imsdId]; + if (row[&MessageRow::direction] == Direction::Incoming && !id.View().empty()) remembered.push_back(ErasedRow{ id }); + } + if (!remembered.empty() && !Write([&] { + erased.Append(std::span(remembered)); + erased.Flush(); })) return 0; - return erased; + std::uint64_t gone = 0; + if (!Write([&] { + gone = table.EraseIf([&](Crafter::DB::Row row) { return row[&MessageRow::conversation] == conversation; }); + if (gone > 0) table.Flush(); + })) + return 0; + return gone; + } + + // The imsd ids of received texts the user deleted, kept until imsd no + // longer lists them: a List does not import them again, and imsd's + // copy is deleted once this session may (at the next List imsd admits + // or after its restart, when polkit refused). False when the store + // refused the write. + bool RememberErased(std::string_view imsdId) { + if (!FitsImsdId(imsdId)) return false; // past imsd's bound: no row carries it + return Write([&] { + erased.Append(ErasedRow{ ImsdId(imsdId) }); + erased.Flush(); + }); + } + + std::unordered_set ErasedImsdIds() const { + std::unordered_set ids; + for (Crafter::DB::Row row : erased) ids.emplace(row[&ErasedRow::imsdId].View()); + return ids; + } + + // Drops the remembered ids a List no longer carries — of those + // remembered before that List was sent (`before`): an id remembered + // while it was in flight belongs to a text its answer could not + // carry, and waits for the next. + void ForgetErased(const std::unordered_set& listed, const std::unordered_set& before) { + if (before.empty()) return; // nothing to forget: no write, no word on the store's state + Write([&] { + const std::uint64_t gone = erased.EraseIf([&](Crafter::DB::Row row) { const std::string id(row[&ErasedRow::imsdId].View()); return before.contains(id) && !listed.contains(id); }); + if (gone > 0) erased.Flush(); + }); } // The row with that imsd id: unique across imsd's runs (ImsdId), so @@ -273,9 +337,10 @@ export namespace ImsdMessages { return std::nullopt; } - // Every imsd id on record. + // Every imsd id on record: the stored texts' and the deleted ones' + // imsd still holds. std::unordered_set ImsdIds() const { - std::unordered_set ids; + std::unordered_set ids = ErasedImsdIds(); for (Crafter::DB::Row row : table) { const ImsdId id = row[&MessageRow::imsdId]; if (!id.View().empty()) ids.emplace(id.View()); @@ -327,21 +392,38 @@ export namespace ImsdMessages { } // The files' length: what a write that needed room grew. - std::uint64_t Length() const noexcept { return table.Stats().fileLength; } + std::uint64_t Length() const noexcept { return table.Stats().fileLength + erased.Stats().fileLength; } bool refused = false; // a write was refused and none has grown a file since public: // Through the gate: a flush that fails at the end of a run is told, // not thrown. - void Flush() { Write([&] { table.Flush(); }); } + void Flush() { + Write([&] { + table.Flush(); + erased.Flush(); + }); + } - // Rewrites the file without tombstones; row ids change, so only at - // start or after a delete with nothing holding ids. - void Compact() { table.Compact(); } + // Rewrites both files without tombstones; the messages' row ids + // change, so only at start or after a delete with nothing holding + // ids (nothing holds an erased id). + void Compact() { + table.Compact(); + erased.Compact(); + } + + // Deleted rows, or the bytes an update or a delete orphaned, still in + // either file: what a Compact would drop. + bool HasDeleted() const noexcept { + const auto garbage = [](const auto& s) { return s.liveCount < s.slotCount || s.heapGarbage > 0; }; + return garbage(table.Stats()) || garbage(erased.Stats()); + } private: - DirectoryLock lock; // before the table: taken first, released last + DirectoryLock lock; // before the tables: taken first, released last Crafter::DB::Table table; + Crafter::DB::Table erased; }; } diff --git a/interfaces/ImsdMessages-Sync.cppm b/interfaces/ImsdMessages-Sync.cppm index 6ea78f1..692bfa4 100644 --- a/interfaces/ImsdMessages-Sync.cppm +++ b/interfaces/ImsdMessages-Sync.cppm @@ -319,6 +319,12 @@ export namespace ImsdMessages { // 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). @@ -349,6 +355,10 @@ export namespace ImsdMessages { } 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); } @@ -365,6 +375,10 @@ export namespace ImsdMessages { 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)); @@ -422,7 +436,7 @@ export namespace ImsdMessages { return; } listInFlight = true; - bus.List([this](ListResult result) { + bus.List([this, before = store.ErasedImsdIds()](ListResult result) { listInFlight = false; if (!result) { // Announced at every failure: the listener's 30 s refresh @@ -446,11 +460,17 @@ export namespace ImsdMessages { status.undeletable = 0; listener.OnStatus(status); } + std::unordered_set 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; diff --git a/tests/Store/main.cpp b/tests/Store/main.cpp index 8f697fb..fea46ca 100644 --- a/tests/Store/main.cpp +++ b/tests/Store/main.cpp @@ -29,6 +29,13 @@ void Check(bool ok, std::string_view what) { } +bool FileHolds(const fs::path& path, std::string_view needle) { + std::ifstream in(path, std::ios::binary); + Check(in.is_open(), "the file opens for the byte check"); + const std::string bytes((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + return bytes.find(needle) != std::string::npos; +} + Message Make(std::string_view conversation, Direction direction, std::int64_t sortTime, std::string_view imsdId, std::string_view text) { Message m; m.conversation = std::string(conversation); @@ -107,10 +114,29 @@ int main() { { MessageStore store(dir); Check(store.Size() == 1, "the row survives a reopen"); + Check(store.ErasedImsdIds() == std::unordered_set{ "ims-sms-in-1-1", "ims-sms-in-1-2" }, "the deleted received texts' imsd ids are remembered across a reopen"); + Check(store.ImsdIds().contains("ims-sms-in-1-1") && !store.ErasedImsdIds().contains("ims-sms-8"), "and count as known; a deleted sent text's id is not remembered"); + store.ForgetErased({ "ims-sms-in-1-2" }, store.ErasedImsdIds()); + Check(store.ErasedImsdIds() == std::unordered_set{ "ims-sms-in-1-2" }, "the ids imsd no longer lists are forgotten"); + Check(FileHolds(dir / "erased.cdb", "ims-sms-in-1-1"), "the forgotten id's bytes are still in the second file"); + Check((fs::status(dir / "erased.cdb").permissions() & (fs::perms::group_all | fs::perms::others_all)) == fs::perms::none, "the second table's file is private"); const std::optional kept = store.Get(1); Check(kept && kept->state == MessageState::Sent && kept->imsdId == "ims-sms-7" && kept->text == "ours", "the updates survive a reopen"); + // The deleted texts' bytes are in the file until a Compact rewrites it. + Check(store.HasDeleted(), "the erased rows are still in the file"); + Check(FileHolds(dir / "messages.cdb", "newer") && FileHolds(dir / "messages.cdb", "older"), "their texts are still in the file"); store.Compact(); Check(store.Size() == 1 && store.Get(0) && store.Get(0)->text == "ours", "Compact renumbers the surviving row"); + Check(!store.HasDeleted(), "nothing deleted is left after it"); + } + { + MessageStore store(dir); + Check(!FileHolds(dir / "erased.cdb", "ims-sms-in-1-1") && FileHolds(dir / "erased.cdb", "ims-sms-in-1-2"), "the forgotten id's bytes are gone from the second file after the Compact, the remembered one's kept"); + Check(!FileHolds(dir / "messages.cdb", "newer") && !FileHolds(dir / "messages.cdb", "older") && FileHolds(dir / "messages.cdb", "ours"), "the deleted texts' bytes are gone after the Compact and a reopen; the kept text's stay"); + store.ForgetErased({}, store.ErasedImsdIds()); + Check(store.HasDeleted(), "a forgotten id alone is something a Compact drops"); + store.Compact(); + Check(!store.HasDeleted() && store.ErasedImsdIds().empty(), "and the second file is rewritten with the first"); } // A process that ends without the destructor's flush, as a crash does: // what Add returned is on disk. diff --git a/tests/Sync/main.cpp b/tests/Sync/main.cpp index f5f65b9..b728c71 100644 --- a/tests/Sync/main.cpp +++ b/tests/Sync/main.cpp @@ -397,6 +397,78 @@ int main() { fs::remove_all(retryDir); } + // --- a message deleted while it is sending: imsd's late answers write nothing ------------- + { + const fs::path deletedDir = fs::temp_directory_path() / "imsd-messages-sync-deleted"; + fs::remove_all(deletedDir); + MessageStore deletedStore(deletedDir); + Fake bus6; + Recorder events6; + Sync deleting(deletedStore, bus6, events6, "31"); + deleting.OnImsdAppeared(); + bus6.AnswerSubscribe(); + bus6.AnswerStatus(Online()); + bus6.AnswerList(std::vector{}); + // A delivered message of an earlier imsd run: its id is its own, and + // no later Send gets it (imsd's ids are unique across its runs). + Message earlier; + earlier.conversation = "+31621308050"; + earlier.peer = "+31621308050"; + earlier.direction = Direction::Outgoing; + earlier.text = "from an earlier imsd run"; + earlier.sortTime = earlier.received = 900; + earlier.state = MessageState::Delivered; + earlier.read = true; + earlier.imsdId = "ims-sms-1700000000-20"; + const std::uint64_t older = *deletedStore.Add(earlier); + const std::uint64_t sent = deleting.Send("+31621308050", "+31621308050", "deleted while it is sending"); + bus6.AnswerSend(std::string("ims-sms-1700000900-1")); + deleting.Erase(sent); + deleting.OnStateChanged("ims-sms-1700000900-1", "sent", ""); + deleting.OnStateChanged("ims-sms-1700000900-1", "delivery-failed", ""); // the report after the sent, for a deleted message + Check(!deletedStore.Get(sent) && deletedStore.Size() == 1, "a message deleted after imsd took it stays deleted when its state comes"); + const std::uint64_t early = deleting.Send("+31621308050", "+31621308050", "deleted before imsd answered"); + deleting.Erase(early); + bus6.AnswerSend(std::string("ims-sms-1700000900-2")); + deleting.OnStateChanged("ims-sms-1700000900-2", "sent", ""); + const std::uint64_t failing = deleting.Send("+31621308051", "+31621308051", "in a conversation deleted before imsd answered"); + deleting.EraseConversation("+31621308051"); + bus6.AnswerSend(std::unexpected(Error(BusError::Kind::Other, "late failure"))); + Check(deletedStore.Size() == 1 && !deletedStore.Get(early) && !deletedStore.Get(failing), "a deleted message stays deleted when imsd's answer to its Send comes"); + Check(std::ranges::count_if(events6.logs, [](const std::string& l) { return l.contains("after it was deleted"); }) == 2 && std::ranges::count_if(events6.logs, [](const std::string& l) { return l.contains("not on record"); }) == 3, "each late answer is logged: the Send answers as deleted, the states as not on record"); + // A received text deleted while imsd still holds its copy (polkit + // refused the delete) is not imported again by a later List; once + // imsd no longer lists it, it is forgotten. + deleting.Refresh(); + bus6.AnswerList(std::vector{ Text("ims-sms-in-9-1", "+31621308052", "kept by imsd", 950) }); + const std::vector conv9 = deletedStore.Conversation("+31621308052"); + Check(conv9.size() == 1, "the text is imported"); + bus6.AnswerDelete(Error(BusError::Kind::AccessDenied, "not authorized")); + deleting.Erase(conv9[0].id); + Check(deletedStore.ErasedImsdIds().contains("ims-sms-in-9-1"), "its imsd id is remembered when the user deletes it"); + deleting.Refresh(); + bus6.AnswerList(std::vector{ Text("ims-sms-in-9-1", "+31621308052", "kept by imsd", 950) }); + Check(deletedStore.Conversation("+31621308052").empty(), "listed again, it is not imported again"); + // A text deleted while a List is in flight: that List's answer is + // older than the memory and does not forget it — it forgets the id + // remembered before it went out; the next one forgets that one too. + deleting.Refresh(); // ims-sms-in-9-1 is remembered as this List goes out + deleting.OnReceived(Text("ims-sms-in-9-2", "+31621308053", "in flight", 960)); + const std::vector conv9b = deletedStore.Conversation("+31621308053"); + Check(conv9b.size() == 1, "a text signalled while a List is in flight is imported"); + bus6.AnswerDelete(Error(BusError::Kind::AccessDenied, "not authorized")); + deleting.Erase(conv9b[0].id); + bus6.AnswerList(std::vector{}); + Check(!deletedStore.ErasedImsdIds().contains("ims-sms-in-9-1") && deletedStore.ErasedImsdIds().contains("ims-sms-in-9-2"), "the List sent before the delete forgets the id remembered before it went out, not the one remembered while it was in flight"); + bus6.AnswerList(std::vector{}); + Check(!deletedStore.ErasedImsdIds().contains("ims-sms-in-9-2"), "the next List, sent after it, forgets that one too"); + // Another client's text (imsd tells every subscriber every state): + // its id is on no record here, and the older message keeps its state. + deleting.OnStateChanged("ims-sms-1700000900-3", "failed", "RP-ERROR cause 38"); + Check(deletedStore.Get(older) && deletedStore.Get(older)->state == MessageState::Delivered && events6.logs.back().contains("not on record"), "a state for another client's text is logged and leaves every message alone"); + fs::remove_all(deletedDir); + } + // --- a restart: a pending send of an earlier run is failed at start; a late word applies --- Message stale; stale.conversation = "+31621308050";