askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
wallet_entries.py · 4.6 KB · 119 lines
| 1 | """Pre-write hook for wallet_entries: you cannot spend what is not there, |
| 2 | and you cannot post the same event twice. |
| 3 | |
| 4 | One rule is code. The other became a declaration. |
| 5 | |
| 6 | ## A provenance marker is used once -- declared, not coded |
| 7 | |
| 8 | Doctrine #7 says a replayed event posts nothing twice. This hook used to |
| 9 | read the ledger for the marker and refuse a repeat; it ran before the write |
| 10 | lock, so two overlapping writers both found nothing and both landed (the |
| 11 | daily `system_wallet_replenish` pass and a by-hand run credited a wallet |
| 12 | twice for one Stripe charge). The schema now declares `generated_from` |
| 13 | unique, which object_records checks inside the lock for every writer, |
| 14 | storage-level ones included, credits and debits alike. A blank marker is |
| 15 | exempt, as before. |
| 16 | |
| 17 | ## You cannot spend what is not there |
| 18 | |
| 19 | The gate sums the ENTRIES rather than reading wallets.balance_minor, even |
| 20 | though that rollup exists and is usually right. A gate must be |
| 21 | authoritative, and a derived caption is not: if the rollup were ever |
| 22 | stale or blank, trusting it would authorize a debit against money that |
| 23 | does not exist (docs/business-logic-patterns.md -- never let a gate read |
| 24 | only a derived value it could recompute). |
| 25 | |
| 26 | Overdraft is a setting rather than a hard zero, because the honest limit |
| 27 | is not always zero: billing.wallet.overdraft_minor lets a high-frequency |
| 28 | API workload tolerate a few cents of race rather than fail a customer's |
| 29 | request mid-flight. Which brings up the thing worth stating plainly |
| 30 | instead of hiding: |
| 31 | |
| 32 | **The known race.** Check-then-append is two steps. Two debits arriving |
| 33 | at the same instant can both pass this gate and both land, taking the |
| 34 | balance slightly below the floor. The write lock serialises the writes |
| 35 | but not the decision. This is tolerated deliberately in v1 -- the |
| 36 | exposure is bounded by the overdraft floor and by how small individual |
| 37 | debits are -- and the real fix (reserve/capture, an auth hold that makes |
| 38 | the check and the claim one atomic act) waits for a workload that |
| 39 | actually shows the race, per doctrine #4. Building a hold system before |
| 40 | a single customer has raced would be inventing a primitive from |
| 41 | imagination. |
| 42 | |
| 43 | Credits are never gated: money arriving is always allowed. |
| 44 | """ |
| 45 | |
| 46 | import os |
| 47 | |
| 48 | import object_records |
| 49 | |
| 50 | DEFAULT_OVERDRAFT_MINOR = 0 |
| 51 | |
| 52 | |
| 53 | def _base_dir(): |
| 54 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 55 | |
| 56 | |
| 57 | def _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 | |
| 67 | def _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 | |
| 74 | def 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 |