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.
promotion_redemptions.py · 2.4 KB · 63 lines
| 1 | """The promotion caps, decided inside the write lock. |
| 2 | |
| 3 | Checkout's gate (object_promotions.blockers) reads the redemption log and |
| 4 | refuses a used-up code, but a read before the write is advisory: twenty |
| 5 | shoppers arriving together all read "0 of 1 used" and all got the |
| 6 | discount. This is the same rule, run by object_records itself holding the |
| 7 | `promotion_redemptions` check lock and the collection's file lock, for |
| 8 | every writer (schema promotion_redemptions.json `locked_checks`). The |
| 9 | verdict is object_promotions.capacity_blockers -- the function the early |
| 10 | gate also calls -- so the two cannot disagree. |
| 11 | |
| 12 | Read-only by contract; fails closed (an unreadable log or promotion is |
| 13 | 503, never "nothing used"). |
| 14 | """ |
| 15 | |
| 16 | import os |
| 17 | |
| 18 | import object_promotions |
| 19 | import object_records |
| 20 | |
| 21 | |
| 22 | def BEFORE_WRITE(request): |
| 23 | """The early, advisory answer: the same verdict, before the lock, so an |
| 24 | API writer gets a clean refusal without queueing for it. The locked |
| 25 | check below is what is atomic.""" |
| 26 | if request.get("action") != "create": |
| 27 | return None |
| 28 | return _verdict(request.get("record") or {}, |
| 29 | os.environ.get("DBBASIC_DATA_DIR", "data")) |
| 30 | |
| 31 | |
| 32 | def LOCKED_CHECK(request): |
| 33 | if request.get("action") != "create": |
| 34 | return None |
| 35 | return _verdict(request.get("record") or {}, request.get("base_dir")) |
| 36 | |
| 37 | |
| 38 | def _verdict(record, base): |
| 39 | promotion_id = str(record.get("promotion_id") or "").strip() |
| 40 | if not promotion_id: |
| 41 | return None |
| 42 | try: |
| 43 | promo = object_records.get_collection_record( |
| 44 | "promotions", promotion_id, base_dir=base) |
| 45 | except object_records.RecordNotFoundError: |
| 46 | # A redemption naming a promotion that does not exist is the |
| 47 | # relation check's business, not a cap's. |
| 48 | return None |
| 49 | except Exception: # noqa: BLE001 |
| 50 | return {"error": "The promotion cannot be read, so its limits cannot be " |
| 51 | "counted; nothing was recorded.", "status": 503} |
| 52 | try: |
| 53 | redemptions = object_records.read_collection_records( |
| 54 | "promotion_redemptions", base_dir=base) |
| 55 | except Exception: # noqa: BLE001 |
| 56 | return {"error": "The redemption log cannot be read, so the code's " |
| 57 | "limits cannot be counted; nothing was recorded.", |
| 58 | "status": 503} |
| 59 | reasons = object_promotions.capacity_blockers( |
| 60 | promo, record.get("customer_email"), redemptions) |
| 61 | if reasons: |
| 62 | return {"error": " ".join(reasons), "status": 409} |
| 63 | return None |