Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_wallet.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_wallet.py · 6.6 KB · 165 lines
1"""Append a debit to a wallet, claiming the balance it was decided from.
2
3A wallet's balance IS its entries (docs/logic-decisions.md: balances are
4derived, never stored), and the only atomic operation the record layer
5offers is a single write. So "this wallet can afford it" holds under a
6race only when the debit itself names what it read: wallet_entries v3
7declares (wallet_id, spend_seq) unique, and a debit carries one more than
8the highest spend_seq among the rows its writer summed. Two debits that
9read the same rows propose the same number, the write lock lets one in,
10and the other re-reads -- now seeing the first -- and decides again.
11
12hook_wallet_entries is the authority on whether a debit fits, but it runs
13before the write lock (AGENTS.md: "hooks cannot close a race"), and a
14trusted server-side write does not run it at all. So callers that must be
15gated pass the hook in as `gate`, asked again on every attempt against the
16rows that attempt read; the spend_seq claim is what makes the gate's yes
17still true at the moment of the write.
18
19Checkout's gift-card spend was the first writer to claim. The template
20runner's hold, its settlement charge and action_resolve_run's charge did
21not, and four overlapping runs held four times against a wallet with room
22for two. Every debit writer now comes through here (doctrine #4: the
23pattern repeated). Credits never claim: giving money back cannot overdraw
24anything, and a credit with a blank spend_seq is exempt from the key.
25"""
26
27from __future__ import annotations
28
29from pathlib import Path
30from typing import Any, Callable
31
32import object_records
33
34ENTRIES = "wallet_entries"
35
36# A lost claim means another debit landed between this writer's read and
37# its write; each retry re-reads. Twenty is the number checkout used.
38ATTEMPTS = 20
39
40
41class Unreadable(Exception):
42 """The wallet's entries cannot be read, so its balance is unknown."""
43
44
45class Refused(Exception):
46 """`compose` or `gate` said no. `message` is the reason, verbatim."""
47
48 def __init__(self, message: str, *, status: int = 402):
49 super().__init__(message)
50 self.message = message
51 self.status = status
52
53
54class AlreadyWritten(Exception):
55 """An entry with this generated_from is already on the ledger: the debit
56 was written before (a retry, a replay, a second settler)."""
57
58 def __init__(self, existing_id: str):
59 super().__init__(f"already written as wallet_entries/{existing_id}")
60 self.existing_id = existing_id
61
62
63class Contended(Exception):
64 """The balance kept moving under this writer for ATTEMPTS reads."""
65
66
67def _int(value: Any) -> int:
68 try:
69 return int(str(value or "0").strip() or "0")
70 except ValueError:
71 return 0
72
73
74def entries_of(wallet_id: str, *, base_dir: Path | str) -> list[dict[str, str]]:
75 """This wallet's entries, strictly: an unreadable ledger is not an empty
76 one, and a balance summed from nothing would authorise anything."""
77 try:
78 rows = object_records.read_collection_records(ENTRIES, base_dir=base_dir)
79 except Exception as exc:
80 raise Unreadable(str(exc)[:160]) from exc
81 return [row for row in rows if str(row.get("wallet_id") or "").strip() == wallet_id]
82
83
84def balance_of(rows) -> int:
85 return sum(_int(row.get("amount_minor")) for row in rows)
86
87
88def next_spend_seq(rows) -> int:
89 return 1 + max((_int(row.get("spend_seq")) for row in rows), default=0)
90
91
92def append_debit(
93 wallet_id: str,
94 compose: dict[str, Any] | Callable[[list[dict[str, str]]], dict[str, Any]],
95 *,
96 base_dir: Path | str,
97 actor: str,
98 gate: Callable[[dict[str, Any]], str] | None = None,
99) -> dict[str, str]:
100 """Write one debit against `wallet_id` and return the stored row.
101
102 `compose` is the entry (amount_minor negative), or a function of the
103 wallet's current rows that returns it -- for a writer whose amount
104 depends on the balance (checkout applies what is left on a card) --
105 and may raise Refused. `gate(entry)` returns "" to allow or the
106 refusal's words. Both are asked again after every lost claim.
107
108 Raises Unreadable, Refused, AlreadyWritten (the entry's generated_from
109 is already on the ledger), Contended, or whatever the write raised.
110 """
111 for _attempt in range(ATTEMPTS):
112 rows = entries_of(wallet_id, base_dir=base_dir)
113 entry = dict(compose(rows) if callable(compose) else compose)
114 entry["wallet_id"] = wallet_id
115 entry["spend_seq"] = str(next_spend_seq(rows))
116 if gate is not None:
117 refusal = gate(entry)
118 if refusal:
119 raise Refused(refusal)
120 try:
121 # preserve_read_only: spend_seq is read_only, so no API client
122 # can write one; the trusted writers here are the ones that claim.
123 return object_records.create_collection_record(
124 ENTRIES, entry, base_dir=base_dir, actor=actor,
125 preserve_read_only=True)
126 except object_records.UniqueConstraintError as exc:
127 if "spend_seq" in exc.fields:
128 continue # another debit landed first: re-read
129 raise AlreadyWritten(exc.existing_id) from exc
130 raise Contended(f"wallet {wallet_id} kept changing for {ATTEMPTS} reads")
131
132
133def write_each_once(entries, *, base_dir: Path | str, actor: str) -> int:
134 """Write a settlement's entries in the order given, each at most once:
135 debits through append_debit (claimed, ungated -- they spend money a
136 hold already reserved), credits through append_once. An entry whose
137 generated_from is already on the ledger is skipped, so a settlement
138 that died part-way is finished by running it again. Returns how many
139 entries this call wrote."""
140 written = 0
141 for entry in entries:
142 if _int(entry.get("amount_minor")) < 0:
143 try:
144 append_debit(str(entry.get("wallet_id") or "").strip(), entry,
145 base_dir=base_dir, actor=actor)
146 except AlreadyWritten:
147 continue
148 written += 1
149 elif append_once(entry, base_dir=base_dir, actor=actor):
150 written += 1
151 return written
152
153
154def append_once(entry: dict[str, Any], *, base_dir: Path | str, actor: str) -> bool:
155 """Write a CREDIT (a release, a reversal) that carries a generated_from,
156 once. Returns False when that marker is already on the ledger -- the
157 replay, retry or second settler the unique key exists to stop."""
158 try:
159 object_records.create_collection_record(ENTRIES, entry, base_dir=base_dir,
160 actor=actor)
161 except object_records.UniqueConstraintError as exc:
162 if "generated_from" in exc.fields:
163 return False
164 raise
165 return True