diff --git a/server/implementations/Catcrafts.Server-Http.cpp b/server/implementations/Catcrafts.Server-Http.cpp index e62ec22..f3eb639 100644 --- a/server/implementations/Catcrafts.Server-Http.cpp +++ b/server/implementations/Catcrafts.Server-Http.cpp @@ -496,12 +496,14 @@ HTTPResponse RenderPage(std::string_view target) { // The financials page: lifetime sales folded live from the order ledger, // donations and expenses from the bank-aggregates file. Server-rendered // here because both inputs are runtime state; the shared dispatch's case - // is the backend-down fallback, like orders. Refolding the ledger per - // request is what every order lookup already does, and the page's whole - // promise is that a refresh shows the current totals — so no caching. + // is the backend-down fallback, like orders. The page's whole promise is + // that a refresh shows the current totals, so the response is not cached: + // the totals are summed on every request, from the fold of the ledger the + // order store holds, which follows the file (LedgerSales). That is a pass + // over orders already in memory, not a read of the ledger from disk, + // which is what this page cost each visitor before 2026-11-26. if (route.kind == RouteKind::Financials) { - const std::vector orders = ListOrders(); - const SalesSummary sales = SummarizeSales(orders); + const SalesSummary sales = LedgerSales(); const Financials fin = CurrentFinancials(); // Shop donations ride along from the same fold: they are live like // sales, and the renderer joins them with the bank-side donations. @@ -1027,8 +1029,25 @@ HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) { unitMinor, parsed.value.quantity, *shippingMinor, parsed.value.country); } + // A token whose reference no other order has. The reference is what a + // payer quotes and a transfer is matched on, and it is only 24 bits of + // the token, so it is checked against the whole ledger rather than left + // to chance (NewUniqueOrderToken has the reasoning). Minted here, after + // validation and both rate limits, so a flood of refused submissions + // never reads the ledger at all. + const std::optional token = NewUniqueOrderToken(); + if (!token) { + std::println(std::cerr, + "checkout: no order reference could be minted that no other " + "order has. The ledger holds too many orders for a six-digit " + "reference; it needs lengthening before checkout can resume"); + return reject({{ "", "Couldn't create the order — something is wrong on this " + "end. Nothing was charged. Please try again later." }}, + parsed.value, "500"); + } + OrderRecord order; - order.token = NewOrderToken(); + order.token = *token; order.reference = ReferenceFromToken(order.token); order.product = product->slug; order.color = parsed.value.color; diff --git a/server/implementations/Catcrafts.Server-Orders.cpp b/server/implementations/Catcrafts.Server-Orders.cpp index 186de77..fdcb55e 100644 --- a/server/implementations/Catcrafts.Server-Orders.cpp +++ b/server/implementations/Catcrafts.Server-Orders.cpp @@ -22,7 +22,13 @@ No permission is granted to copy, modify, distribute, or create derivative works // Current state is a left fold over the file; later events win. Nothing is // ever rewritten, so the log doubles as the audit trail the tax records need, // and a crash mid-write costs at most its own line (a truncated last line is -// skipped by the reader, not fatal). +// skipped by the reader, not fatal, and the next event starts a line of its +// own rather than being written onto the end of the broken one). +// +// The fold is held in memory and redone only when the file changes, so a +// request costs a stat and a lookup, not a parse of the whole history. The +// file stays the one source of truth: an append from the CLI or an edit by +// hand is noticed on the next call (see Ledger, below). // // Why not SQLite yet: single-digit orders per week, one writer, no relations. // The day volume proves that wrong, this imports into a database in one @@ -67,113 +73,274 @@ std::string JsonEscape(std::string_view s) { return out; } +// A reference as a transfer is matched: upper-case letters and digits, nothing +// else. Two references that reduce to the same thing are one reference to the +// bank-transfer rail, so that is the form uniqueness is decided in. +std::string ReferenceKey(std::string_view reference) { + std::string out; + out.reserve(reference.size()); + for (const char c : reference) { + if (c >= '0' && c <= '9') out += c; + else if (c >= 'A' && c <= 'Z') out += c; + else if (c >= 'a' && c <= 'z') out += static_cast(c - 'a' + 'A'); + } + return out; +} + +// ── the fold, kept ──────────────────────────────────────────────────── +// +// The ledger folded into its current state, held in memory between calls and +// folded again only when the FILE changes underneath it. +// +// It used to be folded from disk on every call: every order page, every +// /financials request, every reconciler sweep, and every two seconds for the +// mailer. And each event found its order by walking the orders so far, so the +// fold was quadratic. Neither mattered at a dozen orders. But anyone can add +// orders, and a ledger of 40 000 took twelve seconds to fold (measured +// 2026-11-26), on a path a visitor can hit as often as they like while the +// ledger lock is held. So: orders are found through an index, which makes a +// fold one pass, and the result is kept. +// +// Kept, and still never trusted over the file. The file is the ledger; this +// is a reading of it. Two things other than this process change the file, and +// both have to show up without a restart: `--orders --mark-paid` and its +// siblings append from a second process, and an operator edits fields by hand +// (the erasure request). So every call asks the file what it looks like now, +// one stat, and a different size or modification time means fold it all +// again. What this process appends itself is applied to the held fold by the +// same code that folds a line from disk, so the two cannot come to mean +// different things. +struct Ledger { + std::vector orders; // in the order placed + std::unordered_map byToken; // token -> index in orders + std::set references; // ReferenceKey of every order + // The file does not end in a line break: its last line was cut short by a + // crash mid-write, or it was edited by hand without one. Remembered + // because the next append has to start a line of its own (see AppendLine). + bool tornTail = false; +}; + +// What the file looked like when it was folded. Size catches every append and +// nearly every edit; the modification time catches the edit that keeps the +// size, which is what blanking a name in place is. +struct FileStamp { + bool exists = false; + std::uintmax_t size = 0; + std::filesystem::file_time_type modified{}; + bool operator==(const FileStamp&) const = default; +}; + +Ledger gLedger; +FileStamp gLedgerStamp; +// gLedger is the fold of the file as gLedgerStamp describes it. False until +// the first fold, after SetOrdersPath, and whenever something happened that +// leaves that in doubt; the next reader then folds from disk. +bool gLedgerCurrent = false; + +FileStamp StampOf(const std::filesystem::path& path) { + FileStamp stamp; + if (path.empty()) return stamp; + std::error_code ec; + // One stat: a directory_entry reads size and time together. + const std::filesystem::directory_entry entry(path, ec); + if (ec || !entry.is_regular_file(ec) || ec) return stamp; + stamp.size = entry.file_size(ec); + if (ec) return stamp; + stamp.modified = entry.last_write_time(ec); + if (ec) return stamp; + stamp.exists = true; + return stamp; +} + +// Fold ONE line into the ledger. The whole meaning of the file is here, and +// it is the only place it is: a fold from disk calls this for every line, and +// an append calls it for the line it has just written. A line that is not an +// event (corrupt, cut short, blank) changes nothing — one bad line must not +// take the rest of the ledger with it. +void Apply(Ledger& ledger, std::string_view line) { + const auto doc = Json::Parse(line); + if (!doc || !doc->IsObject()) return; + + auto find = [&](std::string_view token) -> OrderRecord* { + const auto at = ledger.byToken.find(std::string(token)); + return at == ledger.byToken.end() ? nullptr : &ledger.orders[at->second]; + }; + + const std::string_view type = doc->Str("type"); + if (type == "order") { + OrderRecord r; + r.token = std::string(doc->Str("id")); + r.reference = std::string(doc->Str("ref")); + r.product = std::string(doc->Str("product")); + r.color = std::string(doc->Str("color")); + r.quantity = doc->Int("quantity", 1); + r.unitMinor = doc->Int("unit_minor"); + r.createdAt = std::string(doc->Str("at")); + r.updatedAt = r.createdAt; + r.buyer.email = std::string(doc->Str("email")); + r.buyer.name = std::string(doc->Str("name")); + r.buyer.street = std::string(doc->Str("street")); + r.buyer.postal = std::string(doc->Str("postal")); + r.buyer.city = std::string(doc->Str("city")); + r.buyer.country = std::string(doc->Str("country")); + r.goodsMinor = doc->Int("goods_minor"); + r.shippingMinor = doc->Int("shipping_minor"); + r.totalMinor = doc->Int("total_minor"); + r.vatIncluded = doc->Bool("vat_included"); + // Additive key: absent (every pre-donations line) reads false, + // so an old ledger's orders all stay sales. + r.donation = doc->Bool("donation"); + r.status = std::string(doc->Str("status", "awaiting_payment")); + // Read as written, with no default applied here: the ledger + // should keep saying exactly what it recorded, and resolving an + // unexpected value to a rail is PaymentRails::For's single job. + r.payChoice = std::string(doc->Str("pay_choice")); + r.payUrl = std::string(doc->Str("pay_url")); + r.payId = std::string(doc->Str("pay_id")); + if (r.token.empty()) return; + // A duplicate "order" event for an id would be a writer bug; first + // one wins so a replayed line cannot rewrite history. + if (find(r.token)) return; + ledger.byToken.emplace(r.token, ledger.orders.size()); + if (std::string key = ReferenceKey(r.reference); !key.empty()) { + ledger.references.insert(std::move(key)); + } + ledger.orders.push_back(std::move(r)); + } else if (type == "invoice") { + OrderRecord* r = find(doc->Str("id")); + if (!r) return; + r->invoiceNumber = std::string(doc->Str("number")); + r->invoicedAt = std::string(doc->Str("at")); + } else if (type == "notified") { + OrderRecord* r = find(doc->Str("id")); + if (!r) return; + // "what" names the message so a future shipped-notice can share + // the event type without re-marking the confirmation as sent. + if (doc->Str("what") == "confirmation") { + r->confirmationSentAt = std::string(doc->Str("at")); + } + } else if (type == "status") { + OrderRecord* r = find(doc->Str("id")); + if (!r) return; // status for an unknown order: nothing to change + const std::string_view status = doc->Str("status"); + if (status.empty()) return; + r->status = std::string(status); + r->updatedAt = std::string(doc->Str("at")); + if (const std::string_view via = doc->Str("via"); !via.empty()) { + r->paidVia = std::string(via); + } + // The FIRST paid event is the sale, whatever happens later — a + // refund folds the status onward but never unhappens the payment + // (see SummarizeSales). First, not last, so a replayed line + // cannot move the recorded moment. + if (status == "paid" && r->paidAt.empty()) { + r->paidAt = std::string(doc->Str("at")); + } + } +} + +// The ledger as the file has it now: the held fold when the file is as it was +// folded, a fresh fold from disk otherwise. Called with gOrdersMutex held, +// and the reference it returns is good only until the next call that may fold +// or append (AppendLine does both), so nothing keeps it across one. +const Ledger& CurrentLocked() { + const FileStamp before = StampOf(gOrdersPath); + if (gLedgerCurrent && before == gLedgerStamp) return gLedger; + + std::string text; + bool read = true; + if (before.exists) { + std::ifstream in(gOrdersPath, std::ios::binary); + if (in) { + text.assign(std::istreambuf_iterator(in), + std::istreambuf_iterator()); + } else { + read = false; // there and unreadable: an empty fold, and not kept + } + } + + Ledger fresh; + for (std::size_t start = 0; start < text.size();) { + const std::size_t nl = text.find('\n', start); + const std::size_t end = nl == std::string::npos ? text.size() : nl; + Apply(fresh, std::string_view(text).substr(start, end - start)); + if (nl == std::string::npos) break; + start = nl + 1; + } + fresh.tornTail = !text.empty() && text.back() != '\n'; + gLedger = std::move(fresh); + + // Kept only when the file held still while it was read: the same before + // and after, and exactly as many bytes as were folded. A file that + // another process was writing at that moment gives this caller what was + // read, and the next caller a fresh fold. + const FileStamp after = StampOf(gOrdersPath); + gLedgerStamp = after; + gLedgerCurrent = read && after == before + && (after.exists ? after.size == text.size() : text.empty()); + return gLedger; +} + bool AppendLine(const std::string& line) { if (gOrdersPath.empty()) return false; + // Fold first if the file moved, so that what is written below can be + // applied on top of a fold that matches the file it is appended to. + const bool torn = CurrentLocked().tornTail; + const bool current = gLedgerCurrent; + const std::uintmax_t sizeBefore = gLedgerStamp.exists ? gLedgerStamp.size : 0; + // Open per append: orders arrive rarely, and a file reopened each time can // be rotated or edited underneath the running process without a restart. std::ofstream out(gOrdersPath, std::ios::app | std::ios::binary); if (!out) return false; + // A file that ends mid-line gets its line break first. Without it this + // event would be written onto the end of the broken line and be read as + // part of it: a crash that cut one line short would cost the NEXT event + // too, and that event is as likely as not somebody's "paid". + if (torn) out << '\n'; out << line << '\n'; out.flush(); // Report the stream state: a full disk must surface as a visible error, // not a payment link over an order that was never recorded. - return static_cast(out); -} - -// Fold the whole log into id -> record. Corrupt lines are skipped — one bad -// line must not take the rest of the ledger with it. -std::vector FoldLocked() { - std::vector out; - if (gOrdersPath.empty()) return out; - std::ifstream in(gOrdersPath, std::ios::binary); - if (!in) return out; - - auto find = [&](std::string_view token) -> OrderRecord* { - for (OrderRecord& r : out) { - if (r.token == token) return &r; - } - return nullptr; - }; - - std::string line; - while (std::getline(in, line)) { - auto doc = Json::Parse(line); - if (!doc || !doc->IsObject()) continue; - const std::string_view type = doc->Str("type"); - if (type == "order") { - OrderRecord r; - r.token = std::string(doc->Str("id")); - r.reference = std::string(doc->Str("ref")); - r.product = std::string(doc->Str("product")); - r.color = std::string(doc->Str("color")); - r.quantity = doc->Int("quantity", 1); - r.unitMinor = doc->Int("unit_minor"); - r.createdAt = std::string(doc->Str("at")); - r.updatedAt = r.createdAt; - r.buyer.email = std::string(doc->Str("email")); - r.buyer.name = std::string(doc->Str("name")); - r.buyer.street = std::string(doc->Str("street")); - r.buyer.postal = std::string(doc->Str("postal")); - r.buyer.city = std::string(doc->Str("city")); - r.buyer.country = std::string(doc->Str("country")); - r.goodsMinor = doc->Int("goods_minor"); - r.shippingMinor = doc->Int("shipping_minor"); - r.totalMinor = doc->Int("total_minor"); - r.vatIncluded = doc->Bool("vat_included"); - // Additive key: absent (every pre-donations line) reads false, - // so an old ledger's orders all stay sales. - r.donation = doc->Bool("donation"); - r.status = std::string(doc->Str("status", "awaiting_payment")); - // Read as written, with no default applied here: the ledger - // should keep saying exactly what it recorded, and resolving an - // unexpected value to a rail is PaymentRails::For's single job. - r.payChoice = std::string(doc->Str("pay_choice")); - r.payUrl = std::string(doc->Str("pay_url")); - r.payId = std::string(doc->Str("pay_id")); - if (r.token.empty()) continue; - // A duplicate "order" event for an id would be a writer bug; first - // one wins so a replayed line cannot rewrite history. - if (!find(r.token)) out.push_back(std::move(r)); - } else if (type == "invoice") { - OrderRecord* r = find(doc->Str("id")); - if (!r) continue; - r->invoiceNumber = std::string(doc->Str("number")); - r->invoicedAt = std::string(doc->Str("at")); - } else if (type == "notified") { - OrderRecord* r = find(doc->Str("id")); - if (!r) continue; - // "what" names the message so a future shipped-notice can share - // the event type without re-marking the confirmation as sent. - if (doc->Str("what") == "confirmation") { - r->confirmationSentAt = std::string(doc->Str("at")); - } - } else if (type == "status") { - OrderRecord* r = find(doc->Str("id")); - if (!r) continue; // status for an unknown order: skip, keep folding - const std::string_view status = doc->Str("status"); - if (status.empty()) continue; - r->status = std::string(status); - r->updatedAt = std::string(doc->Str("at")); - if (const std::string_view via = doc->Str("via"); !via.empty()) { - r->paidVia = std::string(via); - } - // The FIRST paid event is the sale, whatever happens later — a - // refund folds the status onward but never unhappens the payment - // (see SummarizeSales). First, not last, so a replayed line - // cannot move the recorded moment. - if (status == "paid" && r->paidAt.empty()) { - r->paidAt = std::string(doc->Str("at")); - } - } + if (!out) { + gLedgerCurrent = false; // part of the line may be on disk: fold again + return false; } - return out; + out.close(); + + // Apply the line to the held fold, provided the file grew by exactly what + // was written. If it grew by more, another process appended in the same + // moment and its line is in there unread: fold from disk next time. + const FileStamp after = StampOf(gOrdersPath); + const std::uintmax_t wrote = line.size() + 1 + (torn ? 1 : 0); + if (current && after.exists && after.size == sizeBefore + wrote) { + Apply(gLedger, line); + gLedger.tornTail = false; + gLedgerStamp = after; + } else { + gLedgerCurrent = false; + } + return true; } +// References handed out by NewUniqueOrderToken whose order is not in the +// ledger yet: the gap between minting a token and CreateOrder writing it, +// which is where the payment rail is asked for its link. Guarded by +// gOrdersMutex. A checkout that fails in that gap leaves its entry behind +// until the process restarts, which costs one reference out of sixteen +// million and is not worth a second code path to hand back. +std::set gHeldReferences; + } // namespace void SetOrdersPath(const std::filesystem::path& p) { std::lock_guard lock(gOrdersMutex); gOrdersPath = p; + // Another file, or the same name for a file that has just been replaced: + // either way what is held is not a fold of it. + gLedger = Ledger{}; + gLedgerStamp = FileStamp{}; + gLedgerCurrent = false; } bool CreateOrder(const OrderRecord& o) { @@ -181,7 +348,7 @@ bool CreateOrder(const OrderRecord& o) { // "donation" is written only when true, matching the status writer's // omit-rather-than-empty rule: absent-means-false is what lets a ledger // from before donations existed keep reading correctly. - return AppendLine(std::format( + const bool written = AppendLine(std::format( R"({{"type":"order","at":"{}","id":"{}","ref":"{}","product":"{}",)" R"("color":"{}","quantity":{},"unit_minor":{},)" R"("email":"{}","name":"{}","street":"{}","postal":"{}","city":"{}","country":"{}",)" @@ -196,6 +363,13 @@ bool CreateOrder(const OrderRecord& o) { o.donation ? R"("donation":true,)" : "", JsonEscape(o.status), JsonEscape(o.payChoice), JsonEscape(o.payUrl), JsonEscape(o.payId))); + // The order is in the ledger now, which is where the next mint looks for + // its reference, so the hold NewUniqueOrderToken placed has done its job. + // Kept when the write failed: nothing was stored, and handing the same + // reference straight to the next checkout would only be confusing in the + // log of what went wrong. + if (written) gHeldReferences.erase(ReferenceKey(o.reference)); + return written; } bool AppendOrderStatus(std::string_view token, std::string_view status, @@ -255,12 +429,12 @@ std::optional AssignInvoiceNumber(std::string_view token, // append-only ledger plus the payment provider's records carry the // completeness proof an auditor actually wants. std::lock_guard lock(gOrdersMutex); - const OrderRecord* target = nullptr; - std::vector all = FoldLocked(); - for (const OrderRecord& r : all) { - if (r.token == token) { target = &r; break; } - } - if (!target) return std::nullopt; + // `ledger` and `target` are read up to the append at the end and not + // after it: the append updates the held fold and may replace it. + const Ledger& ledger = CurrentLocked(); + const auto at = ledger.byToken.find(std::string(token)); + if (at == ledger.byToken.end()) return std::nullopt; + const OrderRecord* target = &ledger.orders[at->second]; // Idempotent: a paid order re-processed (manual CLI after the reconciler, // say) keeps its number — a sequence never burns a member on a retry. if (!target->invoiceNumber.empty()) return target->invoiceNumber; @@ -270,7 +444,7 @@ std::optional AssignInvoiceNumber(std::string_view token, const std::string key = CustomerKey(target->buyer.email); std::string customer; std::int64_t maxSeq = 0; - for (const OrderRecord& r : all) { + for (const OrderRecord& r : ledger.orders) { if (r.invoiceNumber.size() < 38 || CustomerKey(r.buyer.email) != key) continue; customer = r.invoiceNumber.substr(0, 36); std::int64_t seq = 0; @@ -299,15 +473,20 @@ bool AppendOrderNotified(std::string_view token, std::string_view isoTimestamp) std::optional FindOrder(std::string_view token) { std::lock_guard lock(gOrdersMutex); - for (OrderRecord& r : FoldLocked()) { - if (r.token == token) return std::move(r); - } - return std::nullopt; + const Ledger& ledger = CurrentLocked(); + const auto at = ledger.byToken.find(std::string(token)); + if (at == ledger.byToken.end()) return std::nullopt; + return ledger.orders[at->second]; } std::vector ListOrders() { std::lock_guard lock(gOrdersMutex); - return FoldLocked(); + return CurrentLocked().orders; +} + +SalesSummary LedgerSales() { + std::lock_guard lock(gOrdersMutex); + return SummarizeSales(CurrentLocked().orders); } SalesSummary SummarizeSales(std::span orders) { @@ -345,6 +524,37 @@ std::string NewOrderToken() { return out; } +std::optional NewUniqueOrderToken() { + return NewUniqueOrderToken([] { return NewOrderToken(); }); +} + +std::optional NewUniqueOrderToken(const std::function& draw) { + std::lock_guard lock(gOrdersMutex); + // Every reference the ledger holds, from the held fold: no pass over the + // file for a checkout. Nothing below folds or appends, so the reference + // stays good for the loop. + const std::set& taken = CurrentLocked().references; + // A draw collides with probability (orders ever placed) / 2^24, so even a + // ledger of a million orders gets through in a couple of draws. The bound + // is there so that a ledger too full to mint for ends in an honest + // refusal at checkout instead of a loop. + for (int i = 0; i < kUniqueTokenDraws; ++i) { + std::string token = draw(); + std::string key = ReferenceKey(ReferenceFromToken(token)); + if (taken.contains(key) || gHeldReferences.contains(key)) continue; + gHeldReferences.insert(std::move(key)); + return token; + } + return std::nullopt; +} + +bool ReferenceInUse(std::string_view reference) { + std::lock_guard lock(gOrdersMutex); + const std::string key = ReferenceKey(reference); + if (key.empty()) return false; + return gHeldReferences.contains(key) || CurrentLocked().references.contains(key); +} + std::string ReferenceFromToken(std::string_view token) { // Derived, not random: an order can never carry a mismatched pair. Six hex // chars is what a human will actually type into a transfer description; at diff --git a/server/interfaces/Catcrafts.Server.cppm b/server/interfaces/Catcrafts.Server.cppm index 01ac4ea..7ea5d59 100644 --- a/server/interfaces/Catcrafts.Server.cppm +++ b/server/interfaces/Catcrafts.Server.cppm @@ -45,6 +45,11 @@ export namespace Catcrafts::Server { // Nothing is ever rewritten in place, so the file is also the audit // trail, and a crash mid-append costs at most the line being written. // + // The fold is held in memory and redone when the file's size or + // modification time changes, so the calls below cost a stat and a lookup + // and still see what the CLI appended or an operator edited a moment ago. + // The file is the ledger; nothing here is trusted over it. + // // The volume argument: this sells single-digit units per week. When that // is wrong by two orders of magnitude, the log imports into SQLite in one // sitting — the reverse migration would not be so kind. @@ -138,6 +143,12 @@ export namespace Catcrafts::Server { }; SalesSummary SummarizeSales(std::span orders); + // The same summary over the ledger as it stands, without handing out a + // copy of every order to get it. /financials is public and uncached and + // asks on every request; ListOrders() would copy the whole ledger each + // time for four integers. + SalesSummary LedgerSales(); + // ── the bank side of /financials ────────────────────────────────── // // Bank-side donations and expenses come from an aggregates file written @@ -199,6 +210,39 @@ export namespace Catcrafts::Server { std::string NewOrderToken(); std::string ReferenceFromToken(std::string_view token); + // A token for a new order whose REFERENCE no other order has, or nullopt + // when none could be found in a bounded number of draws. + // + // The token is 128 bits and never repeats. The reference is its first six + // hex digits, 24 bits, because a person types it into a transfer: two + // orders in a ledger of a few thousand share one often enough to plan + // for, and a transfer quoting it would then be a payment for both. So the + // reference is checked against every order the ledger has ever held, + // paid, lapsed or cancelled alike (an old order's payment is still in the + // bank's history, quoting it), and a colliding token is thrown away for a + // fresh draw. The reference is HELD from this call on, so two checkouts + // minting at the same moment cannot both be handed it; CreateOrder + // releases the hold once the order is in the ledger, where the next call + // finds it. + // + // Checkout mints through this. NewOrderToken stays for what needs only + // the token's shape. + std::optional NewUniqueOrderToken(); + + // The same, drawing candidate tokens from `draw` instead of the CSPRNG, + // and giving up after kUniqueTokenDraws of them. It exists for the + // self-test: a collision is one draw in sixteen million from the real + // generator, so the only way to see a colliding draw thrown away, or a + // run of them end in a refusal, is to hand the draws in. + inline constexpr int kUniqueTokenDraws = 32; + std::optional NewUniqueOrderToken(const std::function& draw); + + // Whether an order with this reference exists, or one is being created. + // Compared the way a transfer is matched, on upper-case alphanumerics, so + // "CC-2B6457" and "cc 2b6457" are one reference. Exported for the + // self-test. + bool ReferenceInUse(std::string_view reference); + // The same reference again, as an ISO 11649 structured creditor reference: // "RF" + two ISO 7064 mod-97-10 check digits + the CC-style body. Derived // from the same token for the same reason, so the two can never disagree. diff --git a/tests/ShouldFoldTheOrderLedger/main.cpp b/tests/ShouldFoldTheOrderLedger/main.cpp index ef9c5dd..93a9382 100644 --- a/tests/ShouldFoldTheOrderLedger/main.cpp +++ b/tests/ShouldFoldTheOrderLedger/main.cpp @@ -116,9 +116,10 @@ Server::OrderRecord Sample(std::string token, std::string email) { // ── buyer free text cannot leave its field ──────────────────────────── // -// Form::ValidateCheckout length-limits name/street/postal/city and nothing -// more, so quotes, backslashes and newlines reach CreateOrder's formatter -// exactly as they were typed. JsonEscape is the only thing between them and +// Form::ValidateCheckout length-limits name/street/postal/city and holds each +// to one line, and nothing more, so quotes and backslashes reach CreateOrder's +// formatter exactly as they were typed (and a newline still can, from any +// caller that is not the form). JsonEscape is the only thing between them and // the record format. void BuyerTextStaysInItsField() { FreshLedger("escaping"); @@ -560,6 +561,427 @@ void ATransitionKeepsWhatItDoesNotName() { } // namespace +// ── a reference names one order ─────────────────────────────────────── +// +// The reference is what a payer quotes and what a transfer is matched on, and +// it is only the first six hex digits of the token: 24 bits, where the token +// has 128. Two orders sharing one would both be paid for by a transfer that +// quotes it. So checkout mints its token through NewUniqueOrderToken, which +// reads every reference the ledger has ever held. +void AReferenceNamesOneOrder() { + FreshLedger("references"); + + Check(!Server::ReferenceInUse("CC-ABCDEF"), + "references: none is in use in an empty ledger"); + + const std::string token = "abcdef0123456789abcdef0123456789"; + Check(Server::CreateOrder(Sample(token, "ada@example.org")), + "references: an order is written"); + Check(Server::ReferenceInUse("CC-ABCDEF"), + "references: a stored order's reference is in use"); + // The same reduction the transfer matcher applies: what settles as one + // reference is one reference here. + Check(Server::ReferenceInUse("cc abcdef"), + "references: however it is spelled"); + Check(!Server::ReferenceInUse("CC-ABCDE0"), + "references: one character different is a different reference"); + Check(!Server::ReferenceInUse(""), "references: an empty one is nobody's"); + + // Lapsed and cancelled orders keep theirs. The payment for an old order + // stays in the bank's history quoting it, so handing the reference to a + // new order would hand that order somebody else's money. + Check(Server::AppendOrderStatus(token, "cancelled", "2026-08-16T09:00:00Z"), + "references: the order is cancelled"); + Check(Server::ReferenceInUse("CC-ABCDEF"), + "references: a cancelled order still holds its reference"); + + // The uniqueness check itself. From the real generator a collision is one + // draw in sixteen million, so checks that only draw from it pass with + // the check deleted (a reviewer deleted it, and they did). Here the draws + // are handed in. A draw that lands on a reference the LEDGER holds is thrown away, + // one that lands on a reference being HELD for a checkout in flight is + // thrown away, and a run of nothing but collisions ends in a refusal + // after a bounded number of draws rather than in a duplicate or a loop. + { + const std::string stored = "abcdef99999999999999999999999999"; // CC-ABCDEF, in the ledger + const std::string first = "0a0b0c11111111111111111111111111"; // CC-0A0B0C, free + const std::string again = "0a0b0c22222222222222222222222222"; // CC-0A0B0C, held by then + const std::string second = "0d0e0f33333333333333333333333333"; // CC-0D0E0F, free + + int draws = 0; + const auto fromLedger = Server::NewUniqueOrderToken([&] { + return ++draws == 1 ? stored : first; + }); + Check(fromLedger && *fromLedger == first, + "references: a draw that collides with a stored order is thrown away", + fromLedger ? *fromLedger : "nothing minted"); + Check(draws == 2, "references: and exactly one more is drawn for it", + std::format("{} draws", draws)); + + draws = 0; + const auto fromHeld = Server::NewUniqueOrderToken([&] { + return ++draws == 1 ? again : second; + }); + Check(fromHeld && *fromHeld == second, + "references: a draw that collides with a reference being held is thrown away", + fromHeld ? *fromHeld : "nothing minted"); + + draws = 0; + const auto none = Server::NewUniqueOrderToken([&] { + ++draws; + return stored; + }); + Check(!none.has_value(), + "references: nothing but collisions is refused, not minted", + none ? *none : ""); + Check(draws == Server::kUniqueTokenDraws, + "references: after the bounded number of draws", + std::format("{} draws", draws)); + } + + // A minted token is well formed, never lands on a reference the ledger + // holds, and its reference is HELD from the moment it is handed out: + // checkout asks the payment rail for its link between minting and + // storing, and a second checkout minting in that gap must not be handed + // the same reference. + std::set minted; + for (int i = 0; i < 64; ++i) { + const std::optional fresh = Server::NewUniqueOrderToken(); + Check(fresh.has_value(), "references: a token can be minted"); + if (!fresh) break; + Check(IsOrderToken(*fresh), "references: a minted token has the token shape", + *fresh); + const std::string reference = Server::ReferenceFromToken(*fresh); + Check(reference != "CC-ABCDEF", + "references: a minted token does not reuse a stored reference", reference); + Check(minted.insert(reference).second, + "references: no two minted tokens share a reference", reference); + Check(Server::ReferenceInUse(reference), + "references: a minted reference is held before its order is stored", + reference); + } + + // Storing the order moves the reference from held to the ledger, and it + // is in use either way. + if (!minted.empty()) { + const std::optional fresh = Server::NewUniqueOrderToken(); + if (fresh) { + Check(Server::CreateOrder(Sample(*fresh, "grace@example.org")), + "references: a minted order is written"); + Check(Server::ReferenceInUse(Server::ReferenceFromToken(*fresh)), + "references: and its reference is in use from the ledger"); + Check(Server::FindOrder(*fresh).has_value(), + "references: the order reads back under its token"); + } + } +} + +// ── the fold is kept, and the file still wins ───────────────────────── +// +// The order store holds the folded ledger in memory and folds it again only +// when the file changes. That is what keeps an order page or /financials from +// costing a parse of the whole history, and it is only acceptable if the held +// fold can never drift from the file. Three things can move the file under a +// running server, and each has to be seen on the very next call: the CLI +// appending from another process, an operator editing a field by hand, and +// the file being replaced outright. And what THIS process appends is applied +// to the held fold directly, so it has to come out identical to a fold of the +// file it was just written to. +bool SameOrders(const std::vector& a, + const std::vector& b) { + if (a.size() != b.size()) return false; + for (std::size_t i = 0; i < a.size(); ++i) { + const Server::OrderRecord& x = a[i]; + const Server::OrderRecord& y = b[i]; + if (x.token != y.token || x.reference != y.reference || x.status != y.status + || x.updatedAt != y.updatedAt || x.paidVia != y.paidVia + || x.paidAt != y.paidAt || x.invoiceNumber != y.invoiceNumber + || x.invoicedAt != y.invoicedAt + || x.confirmationSentAt != y.confirmationSentAt + || x.buyer.name != y.buyer.name || x.buyer.email != y.buyer.email + || x.totalMinor != y.totalMinor || x.donation != y.donation) { + return false; + } + } + return true; +} + +void TheHeldFoldFollowsTheFile() { + const fs::path led = FreshLedger("held-fold"); + const std::string a = "aaaa0000aaaa0000aaaa0000aaaa0000"; + const std::string b = "bbbb1111bbbb1111bbbb1111bbbb1111"; + + Check(Server::CreateOrder(Sample(a, "ada@example.org")), "held: an order is written"); + Check(Server::FindOrder(a).has_value(), "held: and read back"); // now held + + // Another process appends. `--orders FILE --mark-paid TOKEN` does exactly + // this while the server runs, and the mailer must see the paid order on + // its next sweep without anyone restarting anything. + AppendRaw(led, std::format( + R"({{"type":"status","at":"2026-08-15T10:00:00Z","id":"{}","status":"paid","via":"sepa"}})", a)); + { + const auto o = Server::FindOrder(a); + Check(o && o->status == "paid" && o->paidVia == "sepa", + "held: an event another process appended is seen on the next call", + o ? o->status : "order missing"); + } + + // An edit by hand that keeps the file's size, which is what blanking a + // name in place is. Size cannot show it, so the modification time has to. + // The time is SET here rather than waited for, so the check does not + // depend on how finely the filesystem under the scratch directory + // happens to stamp a write made a moment after the last one. + { + std::string text = ReadAll(led); + const std::size_t at = text.find("Ada Lovelace"); + Check(at != std::string::npos, "held: the ledger holds the name as written"); + if (at != std::string::npos) { + const fs::file_time_type stamped = fs::last_write_time(led); + text.replace(at, 12, "xxxxxxxxxxxx"); + { + std::ofstream out(led, std::ios::trunc | std::ios::binary); + out << text; + } + fs::last_write_time(led, stamped + std::chrono::seconds(2)); + const auto o = Server::FindOrder(a); + Check(o && o->buyer.name == "xxxxxxxxxxxx", + "held: an in-place edit that keeps the size is seen by its time", + o ? o->buyer.name : "order missing"); + } + } + + // The file replaced by a different one, as a restored backup would be. + WriteLedger(led, { + R"({"type":"order","at":"2026-08-15T09:30:00Z","id":"bbbb1111bbbb1111bbbb1111bbbb1111","ref":"CC-BBBB11","email":"grace@example.org","total_minor":4200})", + }); + Check(!Server::FindOrder(a).has_value(), + "held: an order the file no longer has is gone from the fold"); + Check(Server::FindOrder(b).has_value(), "held: and the file's own order is there"); + Check(Server::ReferenceInUse("CC-BBBB11") && !Server::ReferenceInUse("CC-AAAA00"), + "held: the references in use follow the file too"); + + // This process's own appends, one of each event, are applied to the held + // fold as they are written. Dropping what is held and folding the file + // from disk has to give the same orders, field for field. + Check(Server::AppendOrderStatus(b, "paid", "2026-08-15T11:00:00Z", "ideal"), + "held: a status event is appended"); + Check(Server::AssignInvoiceNumber(b, "2026-08-15T11:00:01Z").has_value(), + "held: an invoice event is appended"); + Check(Server::AppendOrderNotified(b, "2026-08-15T11:00:02Z"), + "held: a notified event is appended"); + Check(Server::CreateOrder(Sample(a, "ada@example.org")), + "held: an order event is appended"); + Check(Server::AppendOrderStatus(a, "cancelled", "2026-08-15T12:00:00Z"), + "held: a second order's status is appended"); + { + const std::vector held = Server::ListOrders(); + const Server::SalesSummary heldSales = Server::LedgerSales(); + Server::SetOrdersPath(led); // drops what is held; the next call folds the file + const std::vector fresh = Server::ListOrders(); + Check(held.size() == 2 && fresh.size() == 2, + "held: both orders are in the fold either way", + std::format("{} held, {} from disk", held.size(), fresh.size())); + Check(SameOrders(held, fresh), + "held: the fold kept across this process's appends is the fold of the file"); + const Server::SalesSummary summed = Server::SummarizeSales(fresh); + Check(heldSales.count == summed.count && heldSales.totalMinor == summed.totalMinor + && heldSales.donationCount == summed.donationCount + && heldSales.donationsMinor == summed.donationsMinor + && summed.count == 1 && summed.totalMinor == 4200, + "held: LedgerSales is SummarizeSales over the ledger", + std::format("{} sale(s), {}", heldSales.count, heldSales.totalMinor)); + } + + // A line cut short by a crash, with no line break after it. The reader + // has always skipped such a line. What it did NOT survive was the next + // append: written straight onto the end of the broken line, the new + // event became part of it and was skipped along with it, so a crash cost + // two events and the second could be somebody's "paid". The writer now + // starts a line of its own. + { + { + std::ofstream out(led, std::ios::app | std::ios::binary); + out << R"({"type":"status","at":"2026-08-15T13:00:00Z","id":")" << b + << R"(","sta)"; + } + Check(Server::AppendOrderStatus(b, "shipped", "2026-08-15T14:00:00Z"), + "torn: an event is appended after a line cut short"); + const auto o = Server::FindOrder(b); + Check(o && o->status == "shipped", + "torn: the event after a broken line is not lost with it", + o ? o->status : "order missing"); + Server::SetOrdersPath(led); + const auto again = Server::FindOrder(b); + Check(again && again->status == "shipped", + "torn: and a fold from disk reads it the same", + again ? again->status : "order missing"); + } + + // The index. Orders are found through a map from token to position, not + // by walking the list, so what has to hold is that every event lands on + // its own order and on no other, whatever came between. + { + FreshLedger("held-many"); + constexpr int kOrders = 300; + std::vector tokens; + for (int i = 0; i < kOrders; ++i) { + tokens.push_back(std::format("{:08x}{:024x}", i * 7919 + 1, 0)); + Server::CreateOrder(Sample(tokens.back(), std::format("u{}@example.org", i))); + } + for (int i = 0; i < kOrders; i += 3) { + Server::AppendOrderStatus(tokens[i], "paid", "2026-08-15T15:00:00Z", "sepa"); + } + int right = 0; + for (int i = 0; i < kOrders; ++i) { + const auto o = Server::FindOrder(tokens[i]); + const std::string_view want = (i % 3 == 0) ? "paid" : "awaiting_payment"; + if (o && o->token == tokens[i] && o->status == want + && o->buyer.email == std::format("u{}@example.org", i)) { + ++right; + } + } + Check(right == kOrders, + "index: every order is found under its own token, with its own events", + std::format("{} of {}", right, kOrders)); + Check(Server::ListOrders().size() == static_cast(kOrders), + "index: the list holds each order once"); + Check(!Server::FindOrder(std::string(32, 'f')).has_value(), + "index: a token no order has finds nothing"); + } +} + +// ── appends from several threads, and from outside, at once ─────────── +// +// The server appends from the reconciler, the mailer and every request +// thread, while the CLI may append from another process. An append by this +// process is applied to the held fold directly, which is only right if the +// file grew by exactly what was written: if another writer's line landed in +// the same instant, it is in the file and not in the fold, and the fold has +// to be redone. Nothing sequential can show that, so this races them. It can +// only fail when something is wrong (when all is well the held fold equals +// the file whatever the interleaving), and a reviewer who removed the +// "grew by exactly what was written" check saw it fail. +void AppendsFromManyWritersAllLand() { + const fs::path led = FreshLedger("held-threads"); + constexpr int kThreads = 3; + constexpr int kRounds = 150; + + // The outside writer's orders, created before the race so its status + // events always have an order to land on. + std::vector outside; + for (int i = 0; i < 6; ++i) { + outside.push_back(std::format("e{:07x}{:024x}", i, 0)); + Server::CreateOrder(Sample(outside.back(), "outside@example.org")); + } + + std::atomic appended{0}; + std::atomic unseen{0}; + { + std::vector writers; + for (int t = 0; t < kThreads; ++t) { + writers.emplace_back([&, t] { + std::vector mine; + for (int i = 0; i < kRounds; ++i) { + if (mine.empty() || i % 5 == 0) { + mine.push_back(std::format("{:x}{:07x}{:024x}", t, i, 0)); + if (!Server::CreateOrder(Sample(mine.back(), "t@example.org"))) continue; + ++appended; + if (!Server::FindOrder(mine.back())) ++unseen; + } else { + const std::string& token = mine[static_cast(i) % mine.size()]; + const std::string at = std::format("T{}-{}", t, i); + if (!Server::AppendOrderStatus(token, "paid", at, "sepa")) continue; + ++appended; + const auto o = Server::FindOrder(token); + if (!o || o->updatedAt != at) ++unseen; + } + } + }); + } + // The other process: whole lines written straight to the file, the + // way `--orders FILE --mark-shipped` writes them. + writers.emplace_back([&] { + for (int i = 0; i < kRounds; ++i) { + const std::string& token = outside[static_cast(i) % outside.size()]; + const std::string at = std::format("X-{}", i); + AppendRaw(led, std::format( + R"({{"type":"status","at":"{}","id":"{}","status":"shipped"}})", at, token)); + const auto o = Server::FindOrder(token); + if (!o || o->updatedAt != at) ++unseen; + } + }); + } + + Check(unseen.load() == 0, + "threads: every event is in the fold on the call after it was appended", + std::format("{} not seen", unseen.load())); + + const std::vector held = Server::ListOrders(); + const std::string text = ReadAll(led); + const auto lines = std::ranges::count(text, '\n'); + const auto expected = 6 + appended.load() + kRounds; + Check(lines == expected, "threads: the file holds one line for every append", + std::format("{} lines, {} appends", lines, expected)); + + Server::SetOrdersPath(led); // drop what is held and fold the file itself + Check(SameOrders(held, Server::ListOrders()), + "threads: the fold held through the race is the fold of the file"); + + // The case the race above almost never produces, and the one that + // matters. There, the outside writer reads after every line it writes, + // which waits for the ledger lock, so its next line tends to land while + // the other threads are still waking up: before their append has looked + // at the file, where the ordinary "the file changed, fold again" covers + // it. (That race passed with the size check removed, which is how this + // was found.) + // + // What needs the size check is ONE outside line landing in the middle of + // a run of this process's own appends, with nothing from outside after + // it. An append takes the file's stamp when it is done; if it took it + // without noticing that the file grew by more than it wrote, the outside + // line is under that stamp, in the file and not in the fold, and every + // later own append keeps it that way. So each round here is a fresh + // ledger, two threads appending without pause, and a single outside line + // dropped in at a different moment each time, and the fold held at the + // end is compared with the file. Correct code cannot fail this however + // the threads fall; code without the check fails it within a few rounds. + constexpr int kRaces = 120; + int stale = 0; + for (int race = 0; race < kRaces; ++race) { + const fs::path p = FreshLedger("held-race"); + const std::string solo = std::format("f{:07x}{:024x}", race, 0); + Server::CreateOrder(Sample(solo, "outside@example.org")); + std::atomic started{0}; + { + std::vector writers; + for (int t = 0; t < 2; ++t) { + writers.emplace_back([&, t] { + const std::string mine = std::format("{:x}{:07x}{:024x}", t, race, 0); + Server::CreateOrder(Sample(mine, "t@example.org")); + ++started; + for (int i = 0; i < 80; ++i) { + Server::AppendOrderStatus(mine, "paid", + std::format("T{}-{}", t, i), "sepa"); + } + }); + } + writers.emplace_back([&] { + while (started.load() < 2) std::this_thread::yield(); + std::this_thread::sleep_for(std::chrono::microseconds((race * 37) % 1500)); + AppendRaw(p, std::format( + R"({{"type":"status","at":"X-{}","id":"{}","status":"shipped"}})", + race, solo)); + }); + } + const std::vector kept = Server::ListOrders(); + Server::SetOrdersPath(p); + if (!SameOrders(kept, Server::ListOrders())) ++stale; + } + Check(stale == 0, + "threads: a line from outside amid this process's own appends is never missed", + std::format("missed in {} of {} races", stale, kRaces)); +} + int main() { std::error_code ec; // The suites run in parallel, so the scratch directory has to be unique @@ -581,6 +1003,9 @@ int main() { ADonationIsIncomeNeverASale(); OnlyAConfirmationMarksTheEmailSent(); ATransitionKeepsWhatItDoesNotName(); + AReferenceNamesOneOrder(); + TheHeldFoldFollowsTheFile(); + AppendsFromManyWritersAllLand(); fs::remove_all(gWork, ec);