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.
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, |
| 2 | and you cannot post the same event twice. |
| 3 | |
| 4 | Two rules, and the second one arrived later than the first. |
| 5 | |
| 6 | ## Rule 2: a provenance marker is used once |
| 7 | |
| 8 | Doctrine #7 says a replayed event posts nothing twice, and every money |
| 9 | writer 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 |
| 12 | dispute, the template runner stamps `template_run/{id}/{leg}`. But each |
| 13 | of them enforces it the same way: READ the ledger, look for the marker, |
| 14 | then write. That is check-then-write, and it is only as good as the |
| 15 | absence of a second writer between the two steps. |
| 16 | |
| 17 | The second writer is not hypothetical. `system_wallet_replenish` runs on |
| 18 | a daily schedule AND is executable by hand; two overlapping passes both |
| 19 | find no marker and both credit the wallet. The Stripe charge itself is |
| 20 | safe -- that pass sends its marker as Stripe's `idempotency_key`, which |
| 21 | is exactly right and means the CARD is charged once -- but the wallet |
| 22 | credit that follows has no such protection, so the customer is credited |
| 23 | twice for one charge and the shop eats the difference. |
| 24 | |
| 25 | Enforcing it here makes doctrine #7 a property of the collection rather |
| 26 | than a habit of six callers, and it covers writers that do not exist yet: |
| 27 | the image and video handlers coming to app-runner have precisely this |
| 28 | shape. The callers keep their own checks -- a caller that can skip the |
| 29 | work 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 |
| 33 | top-up, an adjustment, an ordinary debit. Uniqueness is a property of the |
| 34 | markers that exist, not a requirement that every entry carry one -- the |
| 35 | same view hook_wallets takes of a blank gift-card code. |
| 36 | |
| 37 | **Both directions are checked**, credits included. That is the case that |
| 38 | motivated the rule, and it is why the marker check runs BEFORE the |
| 39 | "money arriving is never gated" shortcut below: a duplicated credit is |
| 40 | money leaving the business just as surely as a duplicated debit is money |
| 41 | leaving a customer. |
| 42 | |
| 43 | ## Rule 1: you cannot spend what is not there |
| 44 | |
| 45 | The gate sums the ENTRIES rather than reading wallets.balance_minor, even |
| 46 | though that rollup exists and is usually right. A gate must be |
| 47 | authoritative, and a derived caption is not: if the rollup were ever |
| 48 | stale or blank, trusting it would authorize a debit against money that |
| 49 | does not exist (docs/business-logic-patterns.md -- never let a gate read |
| 50 | only a derived value it could recompute). |
| 51 | |
| 52 | Overdraft is a setting rather than a hard zero, because the honest limit |
| 53 | is not always zero: billing.wallet.overdraft_minor lets a high-frequency |
| 54 | API workload tolerate a few cents of race rather than fail a customer's |
| 55 | request mid-flight. Which brings up the thing worth stating plainly |
| 56 | instead of hiding: |
| 57 | |
| 58 | **The known race.** Check-then-append is two steps. Two debits arriving |
| 59 | at the same instant can both pass this gate and both land, taking the |
| 60 | balance slightly below the floor. The write lock serialises the writes |
| 61 | but not the decision. This is tolerated deliberately in v1 -- the |
| 62 | exposure is bounded by the overdraft floor and by how small individual |
| 63 | debits are -- and the real fix (reserve/capture, an auth hold that makes |
| 64 | the check and the claim one atomic act) waits for a workload that |
| 65 | actually shows the race, per doctrine #4. Building a hold system before |
| 66 | a single customer has raced would be inventing a primitive from |
| 67 | imagination. |
| 68 | |
| 69 | Credits are never gated: money arriving is always allowed. |
| 70 | """ |
| 71 | |
| 72 | import os |
| 73 | |
| 74 | import object_records |
| 75 | |
| 76 | DEFAULT_OVERDRAFT_MINOR = 0 |
| 77 | |
| 78 | |
| 79 | def _base_dir(): |
| 80 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 81 | |
| 82 | |
| 83 | def _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 | |
| 93 | def _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 | |
| 100 | def 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 |