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

9 downloads

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, 49 minutes ago History
wallet_entries.py · 4.6 KB · 119 lines
1"""Pre-write hook for wallet_entries: you cannot spend what is not there,
2and you cannot post the same event twice.
3
4One rule is code. The other became a declaration.
5
6## A provenance marker is used once -- declared, not coded
7
8Doctrine #7 says a replayed event posts nothing twice. This hook used to
9read the ledger for the marker and refuse a repeat; it ran before the write
10lock, so two overlapping writers both found nothing and both landed (the
11daily `system_wallet_replenish` pass and a by-hand run credited a wallet
12twice for one Stripe charge). The schema now declares `generated_from`
13unique, which object_records checks inside the lock for every writer,
14storage-level ones included, credits and debits alike. A blank marker is
15exempt, as before.
16
17## You cannot spend what is not there
18
19The gate sums the ENTRIES rather than reading wallets.balance_minor, even
20though that rollup exists and is usually right. A gate must be
21authoritative, and a derived caption is not: if the rollup were ever
22stale or blank, trusting it would authorize a debit against money that
23does not exist (docs/business-logic-patterns.md -- never let a gate read
24only a derived value it could recompute).
25
26Overdraft is a setting rather than a hard zero, because the honest limit
27is not always zero: billing.wallet.overdraft_minor lets a high-frequency
28API workload tolerate a few cents of race rather than fail a customer's
29request mid-flight. Which brings up the thing worth stating plainly
30instead of hiding:
31
32**The known race.** Check-then-append is two steps. Two debits arriving
33at the same instant can both pass this gate and both land, taking the
34balance slightly below the floor. The write lock serialises the writes
35but not the decision. This is tolerated deliberately in v1 -- the
36exposure is bounded by the overdraft floor and by how small individual
37debits are -- and the real fix (reserve/capture, an auth hold that makes
38the check and the claim one atomic act) waits for a workload that
39actually shows the race, per doctrine #4. Building a hold system before
40a single customer has raced would be inventing a primitive from
41imagination.
42
43Credits are never gated: money arriving is always allowed.
44"""
45
46import os
47
48import object_records
49
50DEFAULT_OVERDRAFT_MINOR = 0
51
52
53def _base_dir():
54 return os.environ.get("DBBASIC_DATA_DIR", "data")
55
56
57def _setting(base, key, default):
58 try:
59 for row in object_records.read_collection_records("app_settings", base_dir=base):
60 if row.get("key") == key and str(row.get("value") or "").strip():
61 return row["value"].strip()
62 except Exception:
63 pass
64 return default
65
66
67def _int(value, default=0):
68 try:
69 return int(str(value or "0").strip() or default)
70 except (TypeError, ValueError):
71 return default
72
73
74def BEFORE_WRITE(request):
75 if request.get("action") != "create":
76 return None
77 record = request.get("record") or {}
78
79 amount = _int(record.get("amount_minor"))
80 if amount == 0:
81 return {"error": "A wallet entry of zero moves nothing; record nothing.",
82 "status": 400}
83
84 if amount > 0:
85 return None # money arriving is never gated on balance
86
87 wallet_id = str(record.get("wallet_id") or "").strip()
88 if not wallet_id:
89 return None # required/relation validation owns this
90 base = _base_dir()
91
92 try:
93 entries = object_records.read_collection_records("wallet_entries",
94 base_dir=base)
95 except Exception:
96 # Fails CLOSED. An unreadable ledger means an unknown balance, and
97 # a debit against an unknown balance is how a customer overspends.
98 return {"error": "Wallet ledger is unreadable; refusing to write against "
99 "an unknown balance.", "status": 409}
100
101 # Sum the entries themselves: the gate must not depend on a rollup it
102 # could recompute (see module docstring).
103 balance = 0
104 for row in entries:
105 if row.get("wallet_id") == wallet_id:
106 balance += _int(row.get("amount_minor"))
107
108 floor = -abs(_int(_setting(base, "billing.wallet.overdraft_minor",
109 DEFAULT_OVERDRAFT_MINOR)))
110 remaining = balance + amount
111 if remaining < floor:
112 return {
113 "error": (f"Insufficient wallet balance: this would leave {remaining} "
114 f"(minor units) against a floor of {floor}. Top up, or raise "
115 "app_settings billing.wallet.overdraft_minor if small overdrafts "
116 "are acceptable for this workload."),
117 "status": 402,
118 }
119 return None