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

9 downloads

Install on DigitalOcean 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.

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