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.
usage_rollup.py · 8.9 KB · 228 lines
| 1 | """system_usage_rollup -- fold events into the buckets rating reads. |
| 2 | |
| 3 | POST {today?} -- walks unrated usage_events, puts each in the bucket of |
| 4 | (subscription, metric, the billing period in which it OCCURRED), and writes |
| 5 | or updates the matching usage_summaries row, marking the events rated. |
| 6 | |
| 7 | Why a fold at all, when rating could sum events directly: a month of |
| 8 | per-request rows must not be part of every invoice render, and pricing |
| 9 | must not be welded to the write side's shape. With this bucket in |
| 10 | between, metering can start batching later and no pricing code changes |
| 11 | (plan/billing-metering-spec.md section 2). |
| 12 | |
| 13 | **Usage is bucketed by when it occurred (decision 4, owner, 2026-11-30).** |
| 14 | It used to land in the subscription's CURRENT period at fold time, so 100 |
| 15 | calls made on 29 June and folded after the period rolled over were counted, |
| 16 | and rated against the allowance, in July (finding M11) -- moving overage |
| 17 | between periods and changing what a customer with an allowance pays. Now an |
| 18 | event's occurred_at picks its period: the current one, an earlier period |
| 19 | that already has a summary, or an earlier period counted back from the |
| 20 | current one by the plan's length. Usage is billed in arrears, at the close |
| 21 | of the period it occurred in. |
| 22 | |
| 23 | Idempotent by construction rather than by marker. A summary is not |
| 24 | incremented; it is DERIVED: every event, rated or being folded now, belongs |
| 25 | to exactly one bucket by its own date, so a bucket's value is the sum of |
| 26 | its events, and writing that value twice writes the same value. A re-run |
| 27 | after a crash adds nothing twice, and a period that closed in between (its |
| 28 | summary invoiced from events not yet marked) finds the same value and |
| 29 | writes nothing. |
| 30 | |
| 31 | **What is not decided, and so is not done.** Usage that arrives after its |
| 32 | period was invoiced (a late event for a closed, billed period) would change |
| 33 | a summary somebody has already been billed from; how to bill it -- against |
| 34 | which allowance, on which invoice -- is not settled. Such events are left |
| 35 | UNRATED and reported (late_for_invoiced_period), visible and unbilled, |
| 36 | rather than silently added to a closed bill or moved into the next period. |
| 37 | |
| 38 | Costs are summed alongside quantities, which is what makes margin per |
| 39 | customer per metric a read. |
| 40 | """ |
| 41 | |
| 42 | import os |
| 43 | from datetime import date |
| 44 | from decimal import Decimal, InvalidOperation |
| 45 | |
| 46 | import object_ids |
| 47 | import object_records |
| 48 | |
| 49 | ACTOR = "system_usage_rollup" |
| 50 | _MAX_PERIODS_BACK = 240 |
| 51 | |
| 52 | |
| 53 | def _base_dir(): |
| 54 | return os.environ.get("DBBASIC_DATA_DIR", "data") |
| 55 | |
| 56 | |
| 57 | def _dec(value): |
| 58 | try: |
| 59 | return Decimal(str(value or "0")) |
| 60 | except InvalidOperation: |
| 61 | return Decimal(0) |
| 62 | |
| 63 | |
| 64 | def _int(value): |
| 65 | try: |
| 66 | return int(str(value or "0").strip() or 0) |
| 67 | except (TypeError, ValueError): |
| 68 | return 0 |
| 69 | |
| 70 | |
| 71 | def _truthy(value): |
| 72 | return str(value or "").strip().lower() in ("true", "1", "yes", "on") |
| 73 | |
| 74 | |
| 75 | def _retreat(day_iso, period): |
| 76 | """The same day one period earlier, clamped to the month's end (the |
| 77 | biller's _advance, run backwards).""" |
| 78 | try: |
| 79 | y, m, d = (int(x) for x in str(day_iso)[:10].split("-")) |
| 80 | except (ValueError, AttributeError): |
| 81 | return "" |
| 82 | if period == "year": |
| 83 | y, months = y - 1, m |
| 84 | else: |
| 85 | months = m - 1 |
| 86 | if months < 1: |
| 87 | y, months = y - 1, 12 |
| 88 | for day in (d, 30, 29, 28): |
| 89 | try: |
| 90 | return date(y, months, day).isoformat() |
| 91 | except ValueError: |
| 92 | continue |
| 93 | return "" |
| 94 | |
| 95 | |
| 96 | def _period_of(sub, period, day, known): |
| 97 | """(start, end) of the billing period in which `day` falls: the current |
| 98 | one for anything on or after its start (or undated), else an earlier |
| 99 | period that already has a summary, else one counted back from the |
| 100 | current start by the plan's length. Periods are [start, end).""" |
| 101 | start = str(sub.get("current_period_start") or "")[:10] |
| 102 | end = str(sub.get("current_period_end") or "")[:10] |
| 103 | if not day or not start or day >= start: |
| 104 | return start, end |
| 105 | for s, e in known: |
| 106 | if s and e and s <= day < e: |
| 107 | return s, e |
| 108 | later = start |
| 109 | for _ in range(_MAX_PERIODS_BACK): |
| 110 | earlier = _retreat(later, period) |
| 111 | if not earlier or earlier >= later: |
| 112 | break |
| 113 | if earlier <= day: |
| 114 | return earlier, later |
| 115 | later = earlier |
| 116 | return start, end |
| 117 | |
| 118 | |
| 119 | def POST(request): |
| 120 | base = _base_dir() |
| 121 | today = str(request.get("today") or date.today().isoformat()) |
| 122 | |
| 123 | try: |
| 124 | events = object_records.read_collection_records("usage_events", base_dir=base) |
| 125 | except Exception: |
| 126 | return {"ok": True, "skipped": "metering not installed (usage_events absent)"} |
| 127 | try: |
| 128 | subs = {s["id"]: s for s in |
| 129 | object_records.read_collection_records("subscriptions", base_dir=base)} |
| 130 | except Exception: |
| 131 | subs = {} |
| 132 | try: |
| 133 | plans = {p["id"]: p for p in |
| 134 | object_records.read_collection_records("billing_plans", base_dir=base)} |
| 135 | except Exception: |
| 136 | plans = {} |
| 137 | try: |
| 138 | summaries = object_records.read_collection_records("usage_summaries", base_dir=base) |
| 139 | except Exception: |
| 140 | # Could not look. Folding now could create a second bucket for one |
| 141 | # period; leave the events unrated instead. |
| 142 | return {"ok": True, "skipped": "usage_summaries unreadable; nothing folded", |
| 143 | "today": today} |
| 144 | |
| 145 | existing = {(s.get("subscription_id"), s.get("metric"), |
| 146 | str(s.get("period_start") or "")[:10], |
| 147 | str(s.get("period_end") or "")[:10]): s for s in summaries} |
| 148 | known = {} |
| 149 | for sub_id, metric, start, end in existing: |
| 150 | known.setdefault((sub_id, metric), []).append((start, end)) |
| 151 | |
| 152 | def bucket_of(event): |
| 153 | sub = subs.get(event.get("subscription_id")) |
| 154 | if sub is None: |
| 155 | return None |
| 156 | metric = str(event.get("metric") or "") |
| 157 | plan = plans.get(sub.get("plan_id")) or {} |
| 158 | start, end = _period_of(sub, str(plan.get("period") or "month"), |
| 159 | str(event.get("occurred_at") or "")[:10], |
| 160 | known.get((sub["id"], metric), [])) |
| 161 | return (sub["id"], metric, start, end) |
| 162 | |
| 163 | buckets = {} |
| 164 | orphaned = 0 |
| 165 | for event in events: |
| 166 | if _truthy(event.get("rated")): |
| 167 | continue |
| 168 | key = bucket_of(event) |
| 169 | if key is None: |
| 170 | # Usage with no subscription cannot be priced; leave it |
| 171 | # UNRATED and visible rather than folding it somewhere wrong. |
| 172 | orphaned += 1 |
| 173 | continue |
| 174 | sub = subs[key[0]] |
| 175 | entry = buckets.setdefault(key, {"events": [], "owner_id": sub.get("owner_id", "")}) |
| 176 | entry["events"].append(event["id"]) |
| 177 | |
| 178 | folding = {event_id for entry in buckets.values() for event_id in entry["events"]} |
| 179 | members = {} |
| 180 | for event in events: |
| 181 | if _truthy(event.get("rated")) or event.get("id") in folding: |
| 182 | key = bucket_of(event) |
| 183 | if key is not None: |
| 184 | members.setdefault(key, []).append(event) |
| 185 | |
| 186 | written = 0 |
| 187 | folded = 0 |
| 188 | late = [] |
| 189 | for key, entry in sorted(buckets.items(), key=lambda kv: str(kv[0])): |
| 190 | sub_id, metric, start, end = key |
| 191 | rows = members.get(key, []) |
| 192 | quantity = sum((_dec(row.get("quantity")) for row in rows), Decimal(0)) |
| 193 | count = len(rows) |
| 194 | cost = sum(_int(row.get("cost_minor")) for row in rows) |
| 195 | values = {"quantity": str(quantity), "event_count": str(count), |
| 196 | "cost_minor": str(cost)} |
| 197 | row = existing.get(key) |
| 198 | if row is not None and _truthy(row.get("invoiced")): |
| 199 | if any(str(row.get(field) or "") != value for field, value in values.items()): |
| 200 | # Late usage for a period already billed: not decided how |
| 201 | # to bill it, so it is not folded (see the module doc). |
| 202 | late.append({"subscription": sub_id, "metric": metric, |
| 203 | "period_start": start, "events": len(entry["events"])}) |
| 204 | continue |
| 205 | elif row is not None: |
| 206 | if any(str(row.get(field) or "") != value for field, value in values.items()): |
| 207 | object_records.update_collection_record( |
| 208 | "usage_summaries", row["id"], values, base_dir=base, actor=ACTOR) |
| 209 | elif count: |
| 210 | object_records.create_collection_record( |
| 211 | "usage_summaries", |
| 212 | {"id": object_ids.new_uuid4(), "subscription_id": sub_id, |
| 213 | "metric": metric, "period_start": start, "period_end": end, |
| 214 | **values, "invoiced": "false", |
| 215 | "owner_id": entry["owner_id"]}, |
| 216 | base_dir=base, actor=ACTOR) |
| 217 | written += 1 |
| 218 | for event_id in entry["events"]: |
| 219 | object_records.update_collection_record( |
| 220 | "usage_events", event_id, {"rated": "true"}, |
| 221 | base_dir=base, actor=ACTOR) |
| 222 | folded += 1 |
| 223 | |
| 224 | result = {"ok": True, "today": today, "events_folded": folded, |
| 225 | "summaries_written": written, "orphaned_events": orphaned} |
| 226 | if late: |
| 227 | result["late_for_invoiced_period"] = late |
| 228 | return result |