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
resolve_run.py · 9.7 KB · 216 lines
1"""action_resolve_run -- a person decides a run the machine refused to.
2
3POST {run_id, decision: "charge" | "refund", note?}
4
5`needs_review` is the one state this system creates deliberately and
6cannot leave on its own. A run submitted to a provider whose outcome was
7never learned has money genuinely undecided: releasing the hold gives
8away what we may already have paid, charging bills a customer for work
9that may never have arrived. The sweeper stops there on purpose.
10
11Stopping without a way to continue is not a design, it is an abandoned
12queue -- so this is the other half. It is the ONLY hand that moves a run
13out of needs_review, and it is a person's.
14
15## Why the two decisions are not symmetric
16
17**refund** is the ordinary failure settlement, unchanged: release the
18hold, charge nothing. The operator has decided the customer should not
19pay, whatever it cost us. That cost is already recorded on the run
20(provider_cost_cents), so eating it is a visible number rather than a
21silent one.
22
23**charge** is the debit-plus-release that a successful run gets
24(debit first: see object_template_runs, "The money model"). The
25operator has confirmed the work arrived. Note what this does NOT do: it
26never re-runs anything and never contacts the provider. This verb settles
27money against a job whose fate somebody has established by other means --
28looking in the provider's dashboard, or at the file that landed.
29
30## What it refuses
31
32Only a run actually in `needs_review`. A terminal run is already settled
33and re-settling it is the double-charge the provenance markers exist to
34prevent (they would no-op it, but a verb that silently does nothing is
35worse than one that says why). And a run still `running` is not yours to
36decide -- the provider may still answer, and polling is cheaper and more
37truthful than a guess.
38
39Settlement stays idempotent by the same release/charge markers everything
40else uses, so a double-submitted decision writes money once.
41
42## The claim
43
44The markers keep the MONEY to one settlement; they did not keep the run
45to one decision. Two overlapping submits both read needs_review, the
46second found the first one's money already written, skipped its own, and
47still went on to write the run: the same decision twice answered 200
48twice and stamped a second "Resolved by", and a refund overlapping a
49charge died on the transition guard (succeeded -> failed) as an
50unhandled error. So the run is claimed (template_runs.action_claim,
51object_claims) before its status and the ledger are read, the way every
52other action that composes several writes from one row does. A second
53submit meanwhile is answered 409 in_progress with nothing written; one
54after the first has finished finds the run no longer in needs_review.
55The status is written, and the claim cleared, in one write at the end.
56"""
57
58import os
59
60import object_access
61import object_claims
62import object_collections
63import object_records
64import object_template_runs
65import object_wallet
66
67ACTOR = "action_resolve_run"
68RUNS = "template_runs"
69DECISIONS = ("charge", "refund")
70
71
72def _base_dir():
73 return os.environ.get("DBBASIC_DATA_DIR", "data")
74
75
76def _text(value):
77 return str(value if value is not None else "").strip()
78
79
80def _now():
81 from datetime import datetime, timezone
82 return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
83
84
85def POST(request):
86 request = request or {}
87 base = _base_dir()
88
89 identity = request.get("_identity") or {}
90 user_id = _text(identity.get("user_id"))
91 if not user_id:
92 return {"status": 401,
93 "error": "Resolving a run decides who pays for it, so it "
94 "requires an account."}
95
96 run_id = _text(request.get("run_id"))
97 if not run_id:
98 return {"status": 400, "error": "run_id is required."}
99
100 decision = _text(request.get("decision")).lower()
101 if decision not in DECISIONS:
102 return {"status": 400,
103 "error": (f"decision must be one of {', '.join(DECISIONS)}. "
104 f"'charge' settles the run as delivered (release "
105 f"the hold and debit the stamped price); "
106 f"'refund' settles it as not delivered (release "
107 f"the hold, charge nothing).")}
108
109 try:
110 run = object_records.get_collection_record(RUNS, run_id, base_dir=base)
111 except (object_records.RecordNotFoundError,
112 object_records.InvalidRecordIdError,
113 object_collections.CollectionNotFoundError):
114 return {"status": 404, "error": f"There is no run {run_id!r}."}
115 except Exception as exc:
116 # Unreadable is not missing: "there is no run" told somebody whose
117 # money a parked run holds that it did not exist.
118 return {"status": 503,
119 "error": (f"Run {run_id} could not be read right now "
120 f"({str(exc)[:120]}), so nothing was decided. Try "
121 f"again in a moment.")}
122 if run is None:
123 return {"status": 404, "error": f"There is no run {run_id!r}."}
124
125 # Owner or admin. A run's money is its owner's money. Asked of the
126 # permission engine (whoever may read the run through the
127 # template_runs API: its owner, an admin role in the policy), so the
128 # answer cannot drift from the API's. The registered execute grant
129 # that lets an owner reach this line at all is in rules.json.
130 access = object_access.Access(identity, base_dir=base)
131 if not access.can("read", RUNS, run):
132 return {"status": 403,
133 "error": "Only the run's owner or an admin can resolve it."}
134
135 # THE CLAIM, before the status and the ledger are read (module
136 # docstring, "The claim"). Only the request holding it decides.
137 try:
138 claim, run = object_claims.take(RUNS, run_id, base_dir=base, actor=ACTOR)
139 except object_claims.Busy:
140 return object_claims.busy_answer("run", run_id)
141 except object_records.RecordNotFoundError:
142 return {"status": 404, "error": f"There is no run {run_id!r}."}
143 except Exception as exc:
144 return {"status": 503,
145 "error": (f"Run {run_id} cannot be claimed right now "
146 f"({str(exc)[:120]}), so nothing was decided. Try "
147 f"again in a moment.")}
148 try:
149 return _resolve(request, base, run, run_id, decision, user_id)
150 finally:
151 object_claims.release(RUNS, run_id, claim, base_dir=base, actor=ACTOR)
152
153
154def _resolve(request, base, run, run_id, decision, user_id):
155 """Everything after the claim: read, decide, write."""
156 status = _text(run.get("status"))
157 if status != object_template_runs.NEEDS_REVIEW_STATUS:
158 return {"status": 409,
159 "error": (f"Run {run_id} is {status!r}, not "
160 f"{object_template_runs.NEEDS_REVIEW_STATUS!r}. Only "
161 f"a run the machine refused to decide is yours to "
162 f"decide: a terminal run is already settled, and a "
163 f"running one may still be answered by the provider "
164 f"-- polling is cheaper and more truthful than a "
165 f"guess.")}
166
167 succeeded = decision == "charge"
168
169 # Money first, then status -- the same ordering the runner uses, and
170 # for the same reason: a crash between them leaves money correct and
171 # a status the next pass can see is behind, rather than the reverse.
172 #
173 # An unreadable ledger is NOT an empty one. Read as empty, the
174 # already-settled check cannot see a release that is already there, and
175 # the run is released and charged a second time -- exactly the crash
176 # (money written, status not yet) the markers exist to survive. Refuse
177 # and write nothing; the decision can simply be made again.
178 try:
179 # access: ledger entries of the run read through Access above
180 entries = object_records.read_collection_records("wallet_entries",
181 base_dir=base)
182 except Exception as exc:
183 return {"status": 503,
184 "error": (f"The wallet ledger could not be read "
185 f"({str(exc)[:160]}), so whether run {run_id} is "
186 f"already settled is unknown. Nothing was written; "
187 f"try again once the ledger is readable.")}
188 if object_template_runs.already_settled(run_id, entries):
189 settled = "already settled"
190 else:
191 # The charge is a debit: written first, claiming the balance
192 # (object_wallet), then the release -- each at most once by its
193 # marker, so a double-submitted decision writes money once.
194 written = object_template_runs.settlement(run, succeeded=succeeded)
195 # A charge decision that died after its debit and is now decided
196 # the other way: the refund undoes that charge too.
197 reversal = (None if succeeded
198 else object_template_runs.charge_reversal(run, entries))
199 if reversal and written:
200 written.append(reversal)
201 object_wallet.write_each_once(written, base_dir=base, actor=user_id)
202 settled = "settled" if written else "nothing to settle (free run)"
203
204 note = _text(request.get("note"))
205 resolution = (f"Resolved by {user_id} as {decision} on {_now()}."
206 + (f" {note}" if note else ""))
207 object_records.update_collection_record(
208 RUNS, run_id,
209 {"status": "succeeded" if succeeded else "failed",
210 "error": (_text(run.get("error")) + "\n\n" + resolution)[:2000],
211 "finished_at": _now(), "action_claim": ""},
212 base_dir=base, actor=user_id, preserve_read_only=True)
213
214 return {"status": 200, "ok": True, "run_id": run_id,
215 "decision": decision, "settlement": settled,
216 "resolved_by": user_id}