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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
wallet_entries.py · 7.0 KB · 166 lines
1"""Pre-write hook for wallet_entries: you cannot spend what is not there,
2and you cannot post the same event twice.
3
4Two rules, and the second one arrived later than the first.
5
6## Rule 2: a provenance marker is used once
7
8Doctrine #7 says a replayed event posts nothing twice, and every money
9writer on this box already honours it -- checkout stamps
10`checkout/{order_id}`, the auto top-up stamps
11`auto_topup/{wallet}/{period}/{amount}`, dispute resolution stamps the
12dispute, the template runner stamps `template_run/{id}/{leg}`. But each
13of them enforces it the same way: READ the ledger, look for the marker,
14then write. That is check-then-write, and it is only as good as the
15absence of a second writer between the two steps.
16
17The second writer is not hypothetical. `system_wallet_replenish` runs on
18a daily schedule AND is executable by hand; two overlapping passes both
19find no marker and both credit the wallet. The Stripe charge itself is
20safe -- that pass sends its marker as Stripe's `idempotency_key`, which
21is exactly right and means the CARD is charged once -- but the wallet
22credit that follows has no such protection, so the customer is credited
23twice for one charge and the shop eats the difference.
24
25Enforcing it here makes doctrine #7 a property of the collection rather
26than a habit of six callers, and it covers writers that do not exist yet:
27the image and video handlers coming to app-runner have precisely this
28shape. The callers keep their own checks -- a caller that can skip the
29work entirely should skip it rather than attempt a write and be refused
30-- but the ledger no longer depends on them being right.
31
32**A blank marker is not a collision.** Most entries have none: a manual
33top-up, an adjustment, an ordinary debit. Uniqueness is a property of the
34markers that exist, not a requirement that every entry carry one -- the
35same view hook_wallets takes of a blank gift-card code.
36
37**Both directions are checked**, credits included. That is the case that
38motivated the rule, and it is why the marker check runs BEFORE the
39"money arriving is never gated" shortcut below: a duplicated credit is
40money leaving the business just as surely as a duplicated debit is money
41leaving a customer.
42
43## Rule 1: you cannot spend what is not there
44
45The gate sums the ENTRIES rather than reading wallets.balance_minor, even
46though that rollup exists and is usually right. A gate must be
47authoritative, and a derived caption is not: if the rollup were ever
48stale or blank, trusting it would authorize a debit against money that
49does not exist (docs/business-logic-patterns.md -- never let a gate read
50only a derived value it could recompute).
51
52Overdraft is a setting rather than a hard zero, because the honest limit
53is not always zero: billing.wallet.overdraft_minor lets a high-frequency
54API workload tolerate a few cents of race rather than fail a customer's
55request mid-flight. Which brings up the thing worth stating plainly
56instead of hiding:
57
58**The known race.** Check-then-append is two steps. Two debits arriving
59at the same instant can both pass this gate and both land, taking the
60balance slightly below the floor. The write lock serialises the writes
61but not the decision. This is tolerated deliberately in v1 -- the
62exposure is bounded by the overdraft floor and by how small individual
63debits are -- and the real fix (reserve/capture, an auth hold that makes
64the check and the claim one atomic act) waits for a workload that
65actually shows the race, per doctrine #4. Building a hold system before
66a single customer has raced would be inventing a primitive from
67imagination.
68
69Credits are never gated: money arriving is always allowed.
70"""
71
72import os
73
74import object_records
75
76DEFAULT_OVERDRAFT_MINOR = 0
77
78
79def _base_dir():
80 return os.environ.get("DBBASIC_DATA_DIR", "data")
81
82
83def _setting(base, key, default):
84 try:
85 for row in object_records.read_collection_records("app_settings", base_dir=base):
86 if row.get("key") == key and str(row.get("value") or "").strip():
87 return row["value"].strip()
88 except Exception:
89 pass
90 return default
91
92
93def _int(value, default=0):
94 try:
95 return int(str(value or "0").strip() or default)
96 except (TypeError, ValueError):
97 return default
98
99
100def BEFORE_WRITE(request):
101 if request.get("action") != "create":
102 return None
103 record = request.get("record") or {}
104
105 amount = _int(record.get("amount_minor"))
106 if amount == 0:
107 return {"error": "A wallet entry of zero moves nothing; record nothing.",
108 "status": 400}
109
110 wallet_id = str(record.get("wallet_id") or "").strip()
111 marker = str(record.get("generated_from") or "").strip()
112 base = _base_dir()
113
114 # One read serves both rules. The marker check needs every row (a
115 # marker is unique across the ledger, not per wallet); the balance
116 # needs this wallet's rows.
117 try:
118 entries = object_records.read_collection_records("wallet_entries",
119 base_dir=base)
120 except Exception:
121 # Fails CLOSED, in both directions and for both rules. An
122 # unreadable ledger means an unknown balance AND unknown markers,
123 # and posting into that is how a duplicate becomes permanent.
124 return {"error": "Wallet ledger is unreadable; refusing to write against "
125 "an unknown balance and unknown history.", "status": 409}
126
127 # Rule 2, before the credit shortcut: a duplicated credit is money
128 # leaving the business exactly as a duplicated debit is money leaving
129 # a customer.
130 if marker:
131 for row in entries:
132 if str(row.get("generated_from") or "").strip() == marker:
133 return {
134 "error": (f"This event has already been posted to the "
135 f"ledger ({marker}). A provenance marker is used "
136 f"once: whatever produced it has run before, and "
137 f"posting again would move money twice for one "
138 f"event."),
139 "status": 409,
140 }
141
142 if amount > 0:
143 return None # money arriving is never gated on balance
144
145 if not wallet_id:
146 return None # required/relation validation owns this
147
148 # Sum the entries themselves: the gate must not depend on a rollup it
149 # could recompute (see module docstring).
150 balance = 0
151 for row in entries:
152 if row.get("wallet_id") == wallet_id:
153 balance += _int(row.get("amount_minor"))
154
155 floor = -abs(_int(_setting(base, "billing.wallet.overdraft_minor",
156 DEFAULT_OVERDRAFT_MINOR)))
157 remaining = balance + amount
158 if remaining < floor:
159 return {
160 "error": (f"Insufficient wallet balance: this would leave {remaining} "
161 f"(minor units) against a floor of {floor}. Top up, or raise "
162 "app_settings billing.wallet.overdraft_minor if small overdrafts "
163 "are acceptable for this workload."),
164 "status": 402,
165 }
166 return None