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/tests/test_wallet_debit_claims.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, 19 minutes ago History
test_wallet_debit_claims.py · 8.6 KB · 193 lines
1"""Every writer that takes money out of a wallet claims the balance it read.
2
3wallet_entries declares (wallet_id, spend_seq) unique, and checkout's
4gift-card debit used it: the debit names the next number in the wallet's
5spend sequence from the rows it summed, so of two debits that read the same
6balance only one lands and the other re-reads. The template runner's
7writers did not. hook_wallet_entries is asked before the write lock, so two
8holds placed at the same moment both passed it, and a wallet with room for
9one run paid for four.
10
11And a success settles as a debit plus the release of its hold. Written
12release first, the hold's money was back on the balance for the length of
13one write, and a hold placed in that window spent it a second time: the
14wallet went below zero once the debit landed. The debit is now written
15first, so the balance only ever under-states what is free.
16
17Debits go through object_wallet.append_debit, which claims the sequence
18number, asks the caller's gate on every attempt and re-reads on a lost
19claim. No network: the runs here use the echo handler, and an autouse
20fixture refuses sockets and urllib.
21"""
22
23from __future__ import annotations
24
25import socket
26import urllib.request
27
28import pytest
29
30import object_records
31import test_commerce_action_races as tcr
32import test_template_runner as ttr
33
34
35@pytest.fixture(autouse=True)
36def no_network(monkeypatch):
37 def refuse(*args, **kwargs):
38 raise AssertionError("a test in this file tried to reach the network")
39
40 monkeypatch.setattr(socket.socket, "connect", refuse)
41 monkeypatch.setattr(socket.socket, "connect_ex", refuse)
42 monkeypatch.setattr(socket, "create_connection", refuse)
43 monkeypatch.setattr(urllib.request, "urlopen", refuse)
44 monkeypatch.setattr(urllib.request.OpenerDirector, "open", refuse)
45
46
47data_dir = ttr.data_dir # the runner's fixture: both packages, one root
48
49
50def entries(data_dir):
51 return object_records.read_collection_records("wallet_entries",
52 base_dir=data_dir)
53
54
55@pytest.mark.parametrize("round_", range(3))
56def test_racing_runs_cannot_hold_more_than_the_wallet_has(data_dir, monkeypatch,
57 round_):
58 """Four clicks on Run for a 50-cent template against a 120-cent wallet:
59 every one read 120 before any hold landed (the gate sums the ledger,
60 and the sleep sits after that read). Two may be held; never four."""
61 ttr.seed_template(data_dir)
62 ttr.seed_wallet(data_dir, 120)
63 tcr.widen(monkeypatch, "wallet_entries", 0.03)
64
65 results = tcr.race(4, lambda i: ttr.queue(data_dir))
66
67 assert ttr.balance(data_dir) >= 0, f"wallet at {ttr.balance(data_dir)}"
68 held = [r for r in results if r.get("ok")]
69 assert len(held) == 2, results
70 assert all(r.get("ok") or r.get("status") == 402 for r in results), results
71 runs = object_records.read_collection_records("template_runs", base_dir=data_dir)
72 assert len(runs) == 2
73 seqs = [e["spend_seq"] for e in entries(data_dir) if e["kind"] == "hold"]
74 assert len(set(seqs)) == len(seqs) == 2 and all(seqs), seqs
75
76
77def _hold_inside_the_settlement(data_dir, monkeypatch, settle):
78 """Run `settle()` and, just before it writes the run's charge, queue a
79 second run against the same wallet -- the click that lands while a
80 finished run is being settled. (Release-first wrote the release
81 before this point; debit-first writes nothing before it.)"""
82 real = object_records.create_collection_record
83 seen = []
84
85 def interleaved(collection, record, *a, **k):
86 if (collection == "wallet_entries" and not seen
87 and str(record.get("generated_from", "")).endswith("/charge")):
88 seen.append(record.get("kind"))
89 seen.append(ttr.queue(data_dir))
90 return real(collection, record, *a, **k)
91
92 monkeypatch.setattr(object_records, "create_collection_record", interleaved)
93 result = settle()
94 monkeypatch.setattr(object_records, "create_collection_record", real)
95 assert seen, "the settlement wrote nothing"
96 return result, seen[1]
97
98
99def test_a_hold_placed_while_a_run_settles_cannot_spend_its_money_twice(
100 data_dir, monkeypatch):
101 """A 50-cent wallet, one 50-cent run held and executed. While it is
102 settled a second run is queued. Release-then-debit put the 50 back on
103 the balance for one write, the second hold took it, and the debit then
104 took the wallet to -50."""
105 ttr.seed_template(data_dir)
106 ttr.seed_wallet(data_dir, 50)
107 assert ttr.queue(data_dir)["ok"]
108 assert ttr.balance(data_dir) == 0
109
110 _result, second = _hold_inside_the_settlement(
111 data_dir, monkeypatch, lambda: ttr.run_object("system_template_runner", {}))
112
113 assert ttr.balance(data_dir) >= 0, f"wallet at {ttr.balance(data_dir)}"
114 assert second.get("status") == 402, second
115 assert ttr.balance(data_dir) == 0
116 kinds = sorted(e["kind"] for e in entries(data_dir))
117 assert kinds == ["debit", "hold", "release", "topup"], kinds
118
119
120def test_a_charge_decided_by_hand_cannot_be_spent_twice_either(
121 data_dir, monkeypatch):
122 """action_resolve_run's charge is the same release-plus-debit."""
123 import test_resolve_run as trr
124 ttr.seed_template(data_dir)
125 ttr.seed_wallet(data_dir, 50)
126 object_records.create_collection_record(
127 "wallet_entries",
128 {"wallet_id": "w1", "amount_minor": "-50", "kind": "hold",
129 "generated_from": "template_run/r1/hold", "owner_id": "dan"},
130 base_dir=data_dir)
131 object_records.create_collection_record(
132 "template_runs",
133 {"id": "r1", "template_id": "t1", "template_name": "Greeting",
134 "handler": "echo", "status": "needs_review", "price_cents": "50",
135 "wallet_id": "w1", "owner_id": "dan", "provider_job_id": "job-1"},
136 base_dir=data_dir)
137
138 result, second = _hold_inside_the_settlement(
139 data_dir, monkeypatch,
140 lambda: trr.resolve({"run_id": "r1", "decision": "charge"}))
141
142 assert result["ok"], result
143 assert second.get("status") == 402, second
144 assert ttr.balance(data_dir) == 0, f"wallet at {ttr.balance(data_dir)}"
145
146
147def test_a_settlement_that_died_after_the_debit_is_repaired_by_the_sweeper(
148 data_dir, monkeypatch):
149 """Debit first means a crash can leave the charge without its release
150 (and without the run's status, so its output was never recorded): the
151 wallet is short by the hold, visibly, until the sweeper writes the run
152 off. The sweeper releases the hold and reverses the charge -- the
153 customer has nothing to show for it -- once, however often it runs."""
154 ttr.seed_template(data_dir)
155 ttr.seed_wallet(data_dir, 200)
156 assert ttr.queue(data_dir)["ok"]
157 real = object_records.create_collection_record
158
159 def crash_on_release(collection, record, *a, **k):
160 if collection == "wallet_entries" and record.get("kind") == "release":
161 raise OSError("worker killed before the release")
162 return real(collection, record, *a, **k)
163
164 monkeypatch.setattr(object_records, "create_collection_record", crash_on_release)
165 ttr.run_object("system_template_runner", {})
166 monkeypatch.setattr(object_records, "create_collection_record", real)
167 assert ttr.balance(data_dir) == 100 # hold and debit, no release
168 run = object_records.read_collection_records("template_runs", base_dir=data_dir)[0]
169 assert run["status"] == "claimed"
170
171 later = {"now": "2099-01-01T00:00:00Z"} # long past any heartbeat
172 swept = ttr.run_object("system_run_sweeper", later)
173 assert run["id"] in swept["runs"] and run["id"] in swept["holds_released"]
174 assert ttr.balance(data_dir) == 200, "hold released and the charge reversed"
175 ttr.run_object("system_run_sweeper", later)
176 assert ttr.balance(data_dir) == 200
177 kinds = sorted(e["kind"] for e in entries(data_dir))
178 assert kinds == ["adjustment", "debit", "hold", "release", "topup"], kinds
179
180
181def test_a_successful_run_whose_release_failed_keeps_its_charge(data_dir):
182 """The other half: a run that ended `succeeded` is charged, and the
183 sweeper only hands back its hold."""
184 import object_template_runs
185 run = {"id": "r9", "status": "succeeded", "price_cents": "50",
186 "wallet_id": "w1", "owner_id": "dan"}
187 charge = {"generated_from": "template_run/r9/charge", "amount_minor": "-50",
188 "wallet_id": "w1"}
189 assert object_template_runs.charge_reversal(run, [charge]) is None
190 reversal = object_template_runs.charge_reversal({**run, "status": "abandoned"},
191 [charge])
192 assert reversal["amount_minor"] == "50" and reversal["kind"] == "adjustment"
193 assert reversal["generated_from"] == "template_run/r9/charge_reversal"