orders: the fold is kept in memory, and a reference names one order
The ledger was folded from disk on every call: every order page, every /financials request, every reconciler sweep, and every two seconds for the mailer. Each event found its order by walking the orders so far, so a fold was quadratic. A ledger of 40 000 orders took 11.9 s to fold, anyone can add orders, and /financials is public and uncached. Orders are now found through an index, which makes a fold one pass (0.33 s for the same ledger), and the fold is held in memory. Every call stats the file, and a different size or modification time means fold it again, so an append by the CLI from another process and an edit by hand are seen on the next call without a restart. What this process appends itself is applied to the held fold by the same function that folds a line from disk, provided the file grew by exactly what was written; if it grew by more, another writer's line is in there and the file is folded again. With 40 000 orders /financials takes about 1 ms and an order page 0.3 ms. /financials sums from the held fold through LedgerSales and no longer copies every order to do it. The file stays the ledger and the held fold a reading of it. It costs 3 to 4 KB of memory an order, and it cannot see a change that leaves both the size and the modification time as they were. One thing the writer does differently. A file that ends mid-line, after a crash during a write, now gets its line break before the next event. The next event used to be written onto the end of the broken line and was skipped with it, so a crash cost two events, not one. The reference a payer quotes is the first six hex digits of the token: 24 bits, where two orders in a few thousand share one often enough to plan for, and a transfer quoting it would pay for both. Checkout now mints its token through NewUniqueOrderToken, which reads every reference the ledger has ever held, lapsed and cancelled orders included, and holds the reference while the checkout is in flight. ShouldFoldTheOrderLedger compares the held fold with a fresh one after appends of every kind, an outside append, a same-size edit, a replaced file and a torn tail. It hands colliding draws to the mint, since the real generator collides once in sixteen million. And it races one outside line against a stream of this process's own appends, which fails within a few rounds when the size check is removed. Found in the security review of 2026-11-26. Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
21d34b13ed
commit
06ec1c525c
4 changed files with 810 additions and 112 deletions
|
|
@ -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<OrderRecord> 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<std::string> 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;
|
||||
|
|
|
|||
|
|
@ -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<char>(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<OrderRecord> orders; // in the order placed
|
||||
std::unordered_map<std::string, std::size_t> byToken; // token -> index in orders
|
||||
std::set<std::string> 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<char>(in),
|
||||
std::istreambuf_iterator<char>());
|
||||
} 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<bool>(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<OrderRecord> FoldLocked() {
|
||||
std::vector<OrderRecord> 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<std::string> 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<std::string> 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<OrderRecord> 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<std::string> 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<OrderRecord> 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<OrderRecord> 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<const OrderRecord> orders) {
|
||||
|
|
@ -345,6 +524,37 @@ std::string NewOrderToken() {
|
|||
return out;
|
||||
}
|
||||
|
||||
std::optional<std::string> NewUniqueOrderToken() {
|
||||
return NewUniqueOrderToken([] { return NewOrderToken(); });
|
||||
}
|
||||
|
||||
std::optional<std::string> NewUniqueOrderToken(const std::function<std::string()>& 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<std::string>& 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
|
||||
|
|
|
|||
Loading…
Reference in a new issue