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.
object_claims.py · 6.3 KB · 159 lines
| 1 | """Claim a record before composing the documents that follow from it. |
| 2 | |
| 3 | An action shaped "read what has happened to this row, decide what is |
| 4 | still owed, write the documents" is a check-then-write: two submits that |
| 5 | both read before either writes both write. A double click raised two |
| 6 | shipments for one order, two receipts for one pallet, two purchase orders |
| 7 | to one vendor, two refunds for one returned mug, and four return |
| 8 | authorizations for three shipped mugs. The schema `unique` key and a |
| 9 | derived id (action_apply_count) close that when the decision ends in ONE |
| 10 | write; these end in several (a header, its lines, a status), and a |
| 11 | request arriving between the first and the last of them reads a history |
| 12 | that is half written. |
| 13 | |
| 14 | So the action claims the row first -- a field set with expected_rev, the |
| 15 | one atomic operation the record layer has (AGENTS.md: "a claim is a |
| 16 | compare-and-set, not a write") -- and reads the history it decides from |
| 17 | only once it holds the claim. Every other request that arrives meanwhile |
| 18 | finds a live claim and is told the row is busy; one that read the row |
| 19 | before the claim landed loses the compare-and-set. The claim is released |
| 20 | when the action ends, whatever happened. |
| 21 | |
| 22 | This is the pattern carts.checkout_claim, disputes.resolution_claim and |
| 23 | shipments.label_purchase each wrote by hand, extracted on its fourth and |
| 24 | fifth repetitions (docs/logic-decisions.md #4). Those three keep their |
| 25 | own code: each claim also carries a meaning of its own (the order a cart |
| 26 | is becoming, a label of unknown outcome) that this one deliberately does |
| 27 | not. A claim here means only "somebody is writing from this row". |
| 28 | |
| 29 | The value is `<uuid> <utc iso time>`. A claim older than CLAIM_TTL |
| 30 | belongs to a request that died between claiming and releasing (a crash, |
| 31 | a killed worker); it may be taken over, and the history the next request |
| 32 | reads then shows whatever the dead one did write. The field is read_only |
| 33 | in every schema that carries it, so no API client can set or clear one; |
| 34 | the writers here pass preserve_read_only. |
| 35 | """ |
| 36 | |
| 37 | from __future__ import annotations |
| 38 | |
| 39 | from datetime import datetime, timedelta, timezone |
| 40 | from pathlib import Path |
| 41 | from typing import Any |
| 42 | |
| 43 | import object_ids |
| 44 | import object_records |
| 45 | |
| 46 | FIELD = "action_claim" |
| 47 | CLAIM_TTL = timedelta(minutes=10) |
| 48 | |
| 49 | # How often a compare-and-set is retried when it lost to a write that did |
| 50 | # not claim (a handler restating the order's status, a minted portal |
| 51 | # token). Each retry re-reads the row, so a claim that landed meanwhile is |
| 52 | # seen and answered as busy. |
| 53 | ATTEMPTS = 8 |
| 54 | |
| 55 | |
| 56 | class Busy(Exception): |
| 57 | """Another request holds the claim (or the row would not stay still |
| 58 | long enough to claim). `row` is the freshest copy read.""" |
| 59 | |
| 60 | def __init__(self, row: dict[str, Any]): |
| 61 | super().__init__("record is claimed by another request") |
| 62 | self.row = row |
| 63 | |
| 64 | |
| 65 | def _now() -> datetime: |
| 66 | return datetime.now(timezone.utc) |
| 67 | |
| 68 | |
| 69 | def is_live(claim: str, *, now: datetime | None = None) -> bool: |
| 70 | """True while `claim` may belong to a request that is still running. |
| 71 | An unreadable stamp is treated as live: assume somebody holds it.""" |
| 72 | claim = str(claim or "").strip() |
| 73 | if not claim: |
| 74 | return False |
| 75 | try: |
| 76 | stamped = datetime.fromisoformat(claim.split(" ", 1)[1]) |
| 77 | except (IndexError, ValueError): |
| 78 | return True |
| 79 | if stamped.tzinfo is None: |
| 80 | stamped = stamped.replace(tzinfo=timezone.utc) |
| 81 | return (now or _now()) - stamped < CLAIM_TTL |
| 82 | |
| 83 | |
| 84 | def take( |
| 85 | collection: str, |
| 86 | record_id: str, |
| 87 | *, |
| 88 | base_dir: Path | str, |
| 89 | actor: str, |
| 90 | field: str = FIELD, |
| 91 | ) -> tuple[str, dict[str, str]]: |
| 92 | """Claim `record_id`. Returns (claim, claimed_row). |
| 93 | |
| 94 | Raises Busy when a live claim is held, object_records.RecordNotFoundError |
| 95 | when the row is gone, and whatever the read or write raised otherwise |
| 96 | (the caller decides what an unreadable row means for it; here it is |
| 97 | never "unclaimed"). |
| 98 | """ |
| 99 | row: dict[str, Any] = {} |
| 100 | for _attempt in range(ATTEMPTS): |
| 101 | row = object_records.get_collection_record(collection, record_id, |
| 102 | base_dir=base_dir) |
| 103 | if is_live(str(row.get(field) or "")): |
| 104 | raise Busy(row) |
| 105 | claim = f"{object_ids.new_uuid4()} {_now().isoformat(timespec='seconds')}" |
| 106 | try: |
| 107 | claimed = object_records.update_collection_record( |
| 108 | collection, record_id, {field: claim}, |
| 109 | base_dir=base_dir, actor=actor, preserve_read_only=True, |
| 110 | expected_rev=object_records.compute_record_rev(row)) |
| 111 | except object_records.VersionConflictError: |
| 112 | continue |
| 113 | return claim, claimed |
| 114 | raise Busy(row) |
| 115 | |
| 116 | |
| 117 | def release( |
| 118 | collection: str, |
| 119 | record_id: str, |
| 120 | claim: str, |
| 121 | *, |
| 122 | base_dir: Path | str, |
| 123 | actor: str, |
| 124 | field: str = FIELD, |
| 125 | ) -> bool: |
| 126 | """Clear OUR claim, never somebody else's. Returns True when the row no |
| 127 | longer carries it. Best effort by design: a claim that cannot be |
| 128 | cleared expires after CLAIM_TTL, which is the recovery for a request |
| 129 | that died holding one anyway.""" |
| 130 | for _attempt in range(ATTEMPTS): |
| 131 | try: |
| 132 | current = object_records.get_collection_record( |
| 133 | collection, record_id, base_dir=base_dir) |
| 134 | except object_records.RecordNotFoundError: |
| 135 | return True |
| 136 | except Exception: |
| 137 | return False |
| 138 | if str(current.get(field) or "").strip() != claim: |
| 139 | return True |
| 140 | try: |
| 141 | object_records.update_collection_record( |
| 142 | collection, record_id, {field: ""}, |
| 143 | base_dir=base_dir, actor=actor, preserve_read_only=True, |
| 144 | expected_rev=object_records.compute_record_rev(current)) |
| 145 | return True |
| 146 | except object_records.VersionConflictError: |
| 147 | continue |
| 148 | except Exception: |
| 149 | return False |
| 150 | return False |
| 151 | |
| 152 | |
| 153 | def busy_answer(noun: str, record_id: str) -> dict[str, Any]: |
| 154 | """The 409 a request gets when another one holds the claim.""" |
| 155 | return {"status": 409, "code": "in_progress", "record_id": record_id, |
| 156 | "error": (f"This {noun} is being worked on by another request " |
| 157 | f"right now (a double click, or somebody else at the " |
| 158 | f"same screen). Nothing was written by this one; reload " |
| 159 | f"it in a moment to see what the other one did.")} |