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

0 downloads

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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
usage_events.py · 2.3 KB · 60 lines
1"""Pre-write hook for usage_events: one call, one charge.
2
3Metering's characteristic failure is the duplicate: a client times out,
4retries, and the customer is billed twice for one request. The caller
5supplies an event_id precisely so that retry is safe, and this gate is
6what makes the promise real -- a repeat within the same owner records
7nothing rather than quietly adding to the bill.
8
9Also refuses non-positive quantities. Negative usage is not a
10correction, it is a mistake or an attack: usage is measured, and a
11correction to a bill is a credit on the invoice or a wallet entry, never
12a negative measurement retroactively unmeasuring something that happened
13(docs/logic-decisions.md #3).
14"""
15
16import os
17from decimal import Decimal, InvalidOperation
18
19import object_records
20
21
22def _base_dir():
23 return os.environ.get("DBBASIC_DATA_DIR", "data")
24
25
26def BEFORE_WRITE(request):
27 if request.get("action") != "create":
28 return None
29 record = request.get("record") or {}
30
31 try:
32 quantity = Decimal(str(record.get("quantity") or "0"))
33 except InvalidOperation:
34 return None # schema validation reports the type error properly
35 if quantity <= 0:
36 return {"error": ("Usage quantity must be positive. A correction is a credit "
37 "on the bill, never a negative measurement that unmeasures "
38 "something that already happened."),
39 "status": 400}
40
41 event_id = str(record.get("event_id") or "").strip()
42 if not event_id:
43 return None # required-field validation owns this
44 owner = str(record.get("owner_id") or "")
45
46 try:
47 rows = object_records.read_collection_records("usage_events", base_dir=_base_dir())
48 except Exception:
49 # Unknown history: refusing is the safe direction for money.
50 return {"error": "Usage ledger unreadable; refusing to record against an "
51 "unknown history.", "status": 409}
52 for row in rows:
53 if row.get("event_id") == event_id and str(row.get("owner_id") or "") == owner:
54 return {
55 "error": (f"Usage event {event_id} was already recorded. A retried "
56 "request must not be billed twice -- that is what the "
57 "event key is for."),
58 "status": 409,
59 }
60 return None