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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
timer_actions.py · 10.1 KB · 258 lines
| 1 | """timer_actions -- 62 (Timer): server-enforced start/stop over time_logs. |
| 2 | |
| 3 | plan/vocabulary/62-timer-spec.md. Turns the previously-inert `is_running` |
| 4 | flag into a real invariant: at most one running `time_logs` row per |
| 5 | `owner_id`, and a `duration_seconds` derived (never client-supplied) by |
| 6 | the stop verb. One small object serves three sub-paths -- same "route + |
| 7 | action param" shape app-views' view_render.py and this package's own |
| 8 | site_routes seed row use (`/timers/{action}` -> this object id, |
| 9 | `action` merged into the request payload by object_site_routes.py): |
| 10 | |
| 11 | POST /timers/start {task_id?, notes?} -> stop caller's running |
| 12 | timer if any, start a new one |
| 13 | POST /timers/stop {time_log_id?} -> stop caller's running timer |
| 14 | (or the named one, if theirs) |
| 15 | GET /timers/running -> caller's running row, or null |
| 16 | |
| 17 | Permissions posture: `permissions/rules.json` grants "public execute" on |
| 18 | this object id, same convention as every other site object in the suite |
| 19 | (app-theme's site_style, app-catalog's site_stock -- see |
| 20 | 00-doctrine-and-contract.md's Block Contract) -- authorization happens |
| 21 | INSIDE the handler, not at the route: every action requires a signed-in |
| 22 | identity (401 otherwise) and every read/write is scoped to |
| 23 | `$user_id`/`_identity.user_id`, mirroring what the row-filtered |
| 24 | `time_logs` collection API (`{"owner_id": "$user_id"}` in this package's |
| 25 | own rules.json) would already enforce for a direct PUT. `owner_id` is |
| 26 | always server-set from `_identity`, never accepted from the request body |
| 27 | -- a caller cannot start or stop a timer "as" another owner. |
| 28 | |
| 29 | Concurrency (63, plan/vocabulary/63-concurrency-spec.md): the write that |
| 30 | stops a timer always carries `expected_rev` (`object_records. |
| 31 | compute_record_rev` of the row just read), so a concurrent stop of the |
| 32 | same row fails closed (`VersionConflictError`) instead of double-stopping |
| 33 | -- "fails closed", not silently clobbering. What this does NOT fully |
| 34 | close (62's Storage section names this as the accepted v1 posture, not a |
| 35 | silent gap): two concurrent `POST /timers/start` calls from the SAME |
| 36 | owner could each read "no running timer" before the other's stop-write |
| 37 | commits, and both create a running row -- the classic read-check-write |
| 38 | TOCTOU. Per this repo's own build order, this file does not widen the |
| 39 | collection lock to close that gap (object_records.py's per-call |
| 40 | `.lock` scope is deliberately left alone); it is acceptable at |
| 41 | one-human/one-browser-tab concurrency and is exactly the kind of gap |
| 42 | `record_changes` makes fully visible and correctable if it ever happens, |
| 43 | not a corrupted or vanished record. |
| 44 | """ |
| 45 | |
| 46 | from __future__ import annotations |
| 47 | |
| 48 | import json |
| 49 | import os |
| 50 | from datetime import datetime, timezone |
| 51 | |
| 52 | import object_records |
| 53 | |
| 54 | DATA_DIR_ENV = "DBBASIC_DATA_DIR" |
| 55 | COLLECTION = "time_logs" |
| 56 | FEATURE_FLAGS_COLLECTION = "feature_flags" |
| 57 | TIMERS_ENABLED_FLAG = "timers_enabled" |
| 58 | ACTOR = "timer_actions" |
| 59 | |
| 60 | |
| 61 | def _data_dir() -> str: |
| 62 | # Mirrors app-catalog's stock.py / app-invoices' invoice_totals.py own |
| 63 | # _data_dir(): standalone, reads os.environ directly rather than |
| 64 | # depending on object_server. |
| 65 | return os.environ.get(DATA_DIR_ENV, object_records.DEFAULT_DATA_DIR) |
| 66 | |
| 67 | |
| 68 | def timers_enabled(base_dir) -> bool: |
| 69 | """The block-wide kill switch, `<block>_enabled` convention (00-doctrine- |
| 70 | and-contract.md), a `feature_flags` row named `timers_enabled`. |
| 71 | |
| 72 | Mirrors object_rollups.rollup_pass_enabled's exact posture: default ON |
| 73 | (brownout kill switch, not an adoption gate). A missing row, a |
| 74 | missing/unreadable `feature_flags` collection, and a blank value all |
| 75 | resolve to "on"; only an explicit off/false/0/no value turns it off. |
| 76 | """ |
| 77 | try: |
| 78 | rows = object_records.read_collection_records(FEATURE_FLAGS_COLLECTION, base_dir=base_dir) |
| 79 | except (LookupError, OSError, ValueError): |
| 80 | return True |
| 81 | for row in rows: |
| 82 | if row.get("flag") == TIMERS_ENABLED_FLAG: |
| 83 | value = (row.get("value") or "").strip().lower() |
| 84 | if not value: |
| 85 | return True |
| 86 | return value not in {"off", "false", "0", "no"} |
| 87 | return True |
| 88 | |
| 89 | |
| 90 | def _now_iso() -> str: |
| 91 | return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") |
| 92 | |
| 93 | |
| 94 | def _parse_dt(value) -> datetime | None: |
| 95 | text = str(value or "").strip() |
| 96 | if not text: |
| 97 | return None |
| 98 | try: |
| 99 | return datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 100 | except ValueError: |
| 101 | return None |
| 102 | |
| 103 | |
| 104 | def _find_running(owner_id: str, base_dir: str) -> dict | None: |
| 105 | """Return one owner's running row, or None. |
| 106 | |
| 107 | Expected scale is trivially small (a handful of rows per user per |
| 108 | day, per 62's Storage section) -- a full read + filter, no index. If |
| 109 | more than one running row exists for the owner (the documented |
| 110 | start-race TOCTOU), pick the most recently started one |
| 111 | deterministically rather than file order. |
| 112 | """ |
| 113 | try: |
| 114 | rows = object_records.read_collection_records(COLLECTION, base_dir=base_dir) |
| 115 | except (LookupError, OSError, ValueError): |
| 116 | return None |
| 117 | running = [ |
| 118 | row for row in rows |
| 119 | if row.get("owner_id") == owner_id |
| 120 | and (row.get("is_running") or "").strip().lower() == "true" |
| 121 | ] |
| 122 | if not running: |
| 123 | return None |
| 124 | running.sort(key=lambda row: row.get("started_at") or "", reverse=True) |
| 125 | return running[0] |
| 126 | |
| 127 | |
| 128 | def _stop_row(row: dict, *, base_dir: str) -> dict: |
| 129 | """Stop one already-fetched running row: stamp ended_at/duration_seconds, |
| 130 | compare-and-set against the row's own rev (63) so a concurrent stop of |
| 131 | the same row raises VersionConflictError instead of double-stopping. |
| 132 | """ |
| 133 | started = _parse_dt(row.get("started_at")) |
| 134 | ended_dt = datetime.now(timezone.utc) |
| 135 | duration_seconds = 0 |
| 136 | if started is not None: |
| 137 | duration_seconds = max(0, int((ended_dt - started).total_seconds())) |
| 138 | return object_records.update_collection_record( |
| 139 | COLLECTION, |
| 140 | row["id"], |
| 141 | { |
| 142 | "is_running": "false", |
| 143 | "ended_at": ended_dt.isoformat().replace("+00:00", "Z"), |
| 144 | "duration_seconds": str(duration_seconds), |
| 145 | }, |
| 146 | base_dir=base_dir, |
| 147 | actor=ACTOR, |
| 148 | expected_rev=object_records.compute_record_rev(row), |
| 149 | ) |
| 150 | |
| 151 | |
| 152 | def _start(request: dict, user_id: str, base_dir: str) -> dict: |
| 153 | task_id = str(request.get("task_id") or "").strip() |
| 154 | notes = str(request.get("notes") or "").strip() |
| 155 | |
| 156 | running = _find_running(user_id, base_dir) |
| 157 | if running is not None: |
| 158 | # Open Question resolved per the task brief: starting auto-stops |
| 159 | # the caller's existing timer rather than refusing. Swallow a |
| 160 | # VersionConflictError here -- if a concurrent stop/start already |
| 161 | # changed this row, the outcome this call wanted (the old row no |
| 162 | # longer running) is either already true or this call is racing |
| 163 | # something that will resolve it; either way it must not block |
| 164 | # the new timer from starting. |
| 165 | try: |
| 166 | _stop_row(running, base_dir=base_dir) |
| 167 | except object_records.VersionConflictError: |
| 168 | pass |
| 169 | |
| 170 | record = object_records.create_collection_record( |
| 171 | COLLECTION, |
| 172 | { |
| 173 | "owner_id": user_id, |
| 174 | "task_id": task_id, |
| 175 | "started_at": _now_iso(), |
| 176 | "ended_at": "", |
| 177 | "is_running": "true", |
| 178 | "notes": notes, |
| 179 | }, |
| 180 | base_dir=base_dir, |
| 181 | actor=ACTOR, |
| 182 | ) |
| 183 | _logger.info("timer started", owner_id=user_id, time_log_id=record.get("id", "")) |
| 184 | return _ok({"time_log": record}) |
| 185 | |
| 186 | |
| 187 | def _stop(request: dict, user_id: str, base_dir: str) -> dict: |
| 188 | time_log_id = str(request.get("time_log_id") or "").strip() |
| 189 | |
| 190 | if time_log_id: |
| 191 | try: |
| 192 | row = object_records.get_collection_record(COLLECTION, time_log_id, base_dir=base_dir) |
| 193 | except (object_records.RecordNotFoundError, object_records.InvalidRecordIdError): |
| 194 | return _error(404, f"Time log not found: {time_log_id}") |
| 195 | if row.get("owner_id") != user_id: |
| 196 | return _error(403, "That timer belongs to another owner.") |
| 197 | if (row.get("is_running") or "").strip().lower() != "true": |
| 198 | return _error(409, "That timer is not running.") |
| 199 | else: |
| 200 | row = _find_running(user_id, base_dir) |
| 201 | if row is None: |
| 202 | return _error(409, "No running timer to stop.") |
| 203 | |
| 204 | try: |
| 205 | updated = _stop_row(row, base_dir=base_dir) |
| 206 | except object_records.VersionConflictError: |
| 207 | return _error(409, "Timer changed before it could be stopped; try again.") |
| 208 | |
| 209 | _logger.info("timer stopped", owner_id=user_id, time_log_id=updated.get("id", "")) |
| 210 | return _ok({"time_log": updated}) |
| 211 | |
| 212 | |
| 213 | def _ok(data: dict) -> dict: |
| 214 | body = {"status": "ok"} |
| 215 | body.update(data) |
| 216 | return {"content_type": "application/json", "body": json.dumps(body)} |
| 217 | |
| 218 | |
| 219 | def _error(status: int, message: str, *, code: str | None = None) -> dict: |
| 220 | body = {"status": "error", "error": message} |
| 221 | if code: |
| 222 | body["error_code"] = code |
| 223 | return {"content_type": "application/json", "status": status, "body": json.dumps(body)} |
| 224 | |
| 225 | |
| 226 | def GET(request): |
| 227 | identity = request.get("_identity") or {} |
| 228 | user_id = identity.get("user_id") |
| 229 | if not user_id: |
| 230 | return _error(401, "Sign in to use timers.") |
| 231 | |
| 232 | base_dir = _data_dir() |
| 233 | if not timers_enabled(base_dir): |
| 234 | return _error(400, "Timers are disabled.", code="timers_disabled") |
| 235 | |
| 236 | action = str(request.get("action") or "").strip() |
| 237 | if action != "running": |
| 238 | return _error(404, f"Unknown timer route: /timers/{action or ''}") |
| 239 | |
| 240 | return _ok({"time_log": _find_running(user_id, base_dir)}) |
| 241 | |
| 242 | |
| 243 | def POST(request): |
| 244 | identity = request.get("_identity") or {} |
| 245 | user_id = identity.get("user_id") |
| 246 | if not user_id: |
| 247 | return _error(401, "Sign in to use timers.") |
| 248 | |
| 249 | base_dir = _data_dir() |
| 250 | if not timers_enabled(base_dir): |
| 251 | return _error(400, "Timers are disabled.", code="timers_disabled") |
| 252 | |
| 253 | action = str(request.get("action") or "").strip() |
| 254 | if action == "start": |
| 255 | return _start(request, user_id, base_dir) |
| 256 | if action == "stop": |
| 257 | return _stop(request, user_id, base_dir) |
| 258 | return _error(404, f"Unknown timer route: /timers/{action or ''}") |