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

9 downloads

dbbasic-object-server/object_schedule.py
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, 7 minutes ago History
object_schedule.py · 11.5 KB · 286 lines
1"""``_schedule`` / ``_unschedule``: an object keeps itself fresh.
2
3The askrobots object server injected ``_schedule(interval_seconds,
4method_name)`` and ``_unschedule(method_name=None)`` into every object, and
5objects ported from it still call them: a weather or RSS cache that
6refreshes itself every half hour, a scan processor that drains its inbox
7every 30 seconds. There, the schedule lived in a dict inside one server
8process and was lost on every restart. Here it is a row on the daemon's
9own task board -- the ``task_*`` keys of the ``scheduler`` trigger object
10that ``object_daemon.process_scheduler`` already reads -- so it survives
11restarts, shows up in ``GET /daemon/scheduler/tasks`` and the scheduler
12board, and runs only where the daemon runs.
13
14A self-scheduled row looks like any other task plus two markers::
15
16 {"id": "obj.<object_id>.<method>", "kind": "object_method",
17 "object_id": ..., "method": "refresh", "type": "interval",
18 "schedule": "1800", "interval_seconds": 1800, "next_run": ..., ...}
19
20- One row per (object_id, method): the id is derived from the pair, so
21 scheduling again is an upsert. An unchanged interval leaves the row (and
22 its next_run) untouched -- ported objects call ``_schedule`` on every
23 GET behind a module-level ``_scheduler_registered`` flag that is never
24 set in a fresh process (spawn mode, the sandbox), and resetting next_run
25 on each call would mean the method never ran on a busy object.
26- ``kind: object_method`` tells the daemon that ``method`` is a function
27 name in the object (``tick``, ``refresh``), not an HTTP verb: it is run
28 by exactly that name, called with no arguments when its signature allows
29 (the askrobots calling convention), and never upper-cased.
30- Limits: an interval below ``DBBASIC_SCHEDULE_MIN_INTERVAL_SECONDS``
31 (default 5) is refused for system objects and below
32 ``DBBASIC_SCHEDULE_USER_MIN_INTERVAL_SECONDS`` (default 60) for user
33 objects (``u_<uid>_*``), and one user's objects may hold at most
34 ``DBBASIC_SCHEDULE_USER_MAX_TASKS`` (default 10) self-scheduled rows.
35 The board is therefore bounded: at most one row per object method, and
36 per user a fixed count. Refusals raise ``ScheduleError`` (a ValueError)
37 in the calling object -- never a silent no-op.
38
39User objects reach this only through the sandbox's helper proxy, which
40binds the call to the calling object's own id (``object_sandbox``); the
41daemon then runs the method on the normal path, so a user object runs
42sandboxed with no identity of anyone's, and a system object runs as it
43always does. Destroying an object (``DELETE /objects/{id}?destroy=true``)
44removes its self-scheduled rows; package-declared schedules are left to
45their package.
46"""
47from __future__ import annotations
48
49import json
50import math
51import os
52import time
53from datetime import datetime, timezone
54from pathlib import Path
55from typing import Any, Callable
56
57import object_state
58from object_sandbox import HTTP_VERB_NAMES, SCHEDULED_METHOD_RE, ScheduleError
59from object_versions import DEFAULT_DATA_DIR
60
61SCHEDULER_OBJECT_ID = "scheduler"
62SCHEDULER_PREFIX = "task_"
63TASK_KIND = "object_method"
64TASK_TYPE = "interval"
65
66MIN_INTERVAL_ENV = "DBBASIC_SCHEDULE_MIN_INTERVAL_SECONDS"
67USER_MIN_INTERVAL_ENV = "DBBASIC_SCHEDULE_USER_MIN_INTERVAL_SECONDS"
68USER_MAX_TASKS_ENV = "DBBASIC_SCHEDULE_USER_MAX_TASKS"
69DEFAULT_MIN_INTERVAL_SECONDS = 5
70DEFAULT_USER_MIN_INTERVAL_SECONDS = 60
71DEFAULT_USER_MAX_TASKS = 10
72
73
74def _env_int(name: str, default: int, minimum: int) -> int:
75 try:
76 value = int(os.environ.get(name, "").strip() or default)
77 except ValueError:
78 return default
79 return max(value, minimum)
80
81
82def min_interval_seconds(*, user: bool) -> int:
83 if user:
84 return _env_int(USER_MIN_INTERVAL_ENV, DEFAULT_USER_MIN_INTERVAL_SECONDS, 1)
85 return _env_int(MIN_INTERVAL_ENV, DEFAULT_MIN_INTERVAL_SECONDS, 1)
86
87
88def user_max_tasks() -> int:
89 return _env_int(USER_MAX_TASKS_ENV, DEFAULT_USER_MAX_TASKS, 0)
90
91
92def task_id(object_id: str, method: str) -> str:
93 return f"obj.{object_id}.{method}"
94
95
96def task_key(object_id: str, method: str) -> str:
97 return f"{SCHEDULER_PREFIX}{task_id(object_id, method)}"
98
99
100def _user_uid(object_id: str) -> str | None:
101 import object_runtime_helpers
102
103 return object_runtime_helpers._user_namespace(object_id)
104
105
106def _clean_method(method_name: Any) -> str:
107 if not isinstance(method_name, str) or not SCHEDULED_METHOD_RE.fullmatch(method_name):
108 raise ScheduleError(
109 f"method_name must name a public function of the object (letters, digits, "
110 f"underscores, not starting with '_'), got {method_name!r}"
111 )
112 if method_name in HTTP_VERB_NAMES:
113 raise ScheduleError(
114 f"{method_name!r} is an HTTP method name, not a function to schedule; "
115 "give the scheduled function its own name (for example 'refresh')"
116 )
117 return method_name
118
119
120def _clean_interval(interval_seconds: Any, *, user: bool) -> int:
121 if isinstance(interval_seconds, bool) or not isinstance(interval_seconds, (int, float)):
122 raise ScheduleError("interval_seconds must be a number of seconds")
123 if not math.isfinite(interval_seconds):
124 raise ScheduleError("interval_seconds must be finite")
125 interval = int(math.ceil(interval_seconds))
126 floor = min_interval_seconds(user=user)
127 if interval < floor:
128 who = "a user object" if user else "an object"
129 raise ScheduleError(f"interval_seconds must be at least {floor} for {who}, got {interval_seconds!r}")
130 return interval
131
132
133def _iso(epoch: int) -> str:
134 return datetime.fromtimestamp(epoch, timezone.utc).isoformat().replace("+00:00", "Z")
135
136
137def _rows(state: dict[str, Any]):
138 for key, value in state.items():
139 if not key.startswith(SCHEDULER_PREFIX):
140 continue
141 try:
142 row = json.loads(value) if isinstance(value, str) else None
143 except (TypeError, ValueError):
144 continue
145 if isinstance(row, dict):
146 yield key, row
147
148
149def _manager(base_dir: Path | str) -> object_state.ObjectStateManager:
150 return object_state.ObjectStateManager(SCHEDULER_OBJECT_ID, base_dir=base_dir, load=False)
151
152
153def schedule(
154 object_id: str,
155 method_name: Any,
156 interval_seconds: Any,
157 *,
158 base_dir: Path | str = DEFAULT_DATA_DIR,
159 now: int | None = None,
160) -> dict[str, Any]:
161 """Create or update the one interval task for (object_id, method_name)."""
162 method = _clean_method(method_name)
163 uid = _user_uid(object_id)
164 interval = _clean_interval(interval_seconds, user=uid is not None)
165 current = int(time.time() if now is None else now)
166 key = task_key(object_id, method)
167 actor = f"object:{object_id}"
168
169 def change(state: dict[str, Any]) -> dict[str, Any]:
170 existing = None
171 if key in state:
172 existing = next((row for k, row in _rows({key: state[key]})), None)
173 if existing is not None:
174 row = dict(existing)
175 unchanged = (row.get("interval_seconds") == interval and row.get("status") == "active"
176 and row.get("type") == TASK_TYPE and row.get("kind") == TASK_KIND)
177 if unchanged:
178 return row
179 row.update({
180 "type": TASK_TYPE, "kind": TASK_KIND, "schedule": str(interval),
181 "interval_seconds": interval, "status": "active",
182 "next_run": current + interval, "updated_at": current,
183 "updated_at_iso": _iso(current), "updated_by": actor,
184 })
185 row.pop("error", None)
186 else:
187 if uid is not None:
188 owned = sum(
189 1 for _k, r in _rows(state)
190 if r.get("kind") == TASK_KIND and _user_uid(str(r.get("object_id") or "")) == uid
191 )
192 cap = user_max_tasks()
193 if owned >= cap:
194 raise ScheduleError(
195 f"user {uid} already has {owned} scheduled method(s); the limit is {cap} "
196 f"({USER_MAX_TASKS_ENV}). Unschedule one first."
197 )
198 row = {
199 "id": task_id(object_id, method), "kind": TASK_KIND,
200 "object_id": object_id, "method": method, "payload": {},
201 "type": TASK_TYPE, "schedule": str(interval), "interval_seconds": interval,
202 "status": "active", "next_run": current + interval, "last_run": None,
203 "run_count": 0, "created_at": current, "created_at_iso": _iso(current),
204 "created_by": actor, "updated_at": current, "updated_at_iso": _iso(current),
205 "updated_by": actor,
206 }
207 state[key] = json.dumps(row, sort_keys=True, separators=(",", ":"))
208 return row
209
210 return _manager(base_dir).modify(change)
211
212
213def unschedule(
214 object_id: str,
215 method_name: Any = None,
216 *,
217 base_dir: Path | str = DEFAULT_DATA_DIR,
218) -> int:
219 """Remove this object's self-scheduled task for one method, or all of
220 them (method_name None). Returns how many rows went; 0 is not an error,
221 matching the old runtime."""
222 method = None if method_name is None else _clean_method(method_name)
223
224 def change(state: dict[str, Any]) -> int:
225 doomed = [
226 key for key, row in _rows(state)
227 if row.get("kind") == TASK_KIND and row.get("object_id") == object_id
228 and (method is None or row.get("method") == method)
229 ]
230 for key in doomed:
231 del state[key]
232 return len(doomed)
233
234 return _manager(base_dir).modify(change)
235
236
237def list_object_tasks(object_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> list[dict[str, Any]]:
238 """What an object has scheduled for itself, for its owner to read.
239
240 Only the fields an owner needs: which method, how often, when it next
241 and last ran, how many times, and the last error if the daemon recorded
242 one. No ids of other objects, no actor names.
243 """
244 manager = _manager(base_dir)
245 manager.reload()
246 out: list[dict[str, Any]] = []
247 for _key, row in _rows(manager.get_all()):
248 if row.get("kind") != TASK_KIND or row.get("object_id") != object_id:
249 continue
250 item = {
251 "method": row.get("method"),
252 "status": row.get("status"),
253 "interval_seconds": row.get("interval_seconds"),
254 "next_run": row.get("next_run"),
255 "last_run": row.get("last_run"),
256 "run_count": row.get("run_count", 0),
257 }
258 last_error = row.get("last_error") or row.get("error")
259 if last_error:
260 item["last_error"] = str(last_error)[:500]
261 out.append(item)
262 out.sort(key=lambda item: str(item["method"]))
263 return out
264
265
266def remove_object_tasks(object_id: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> int:
267 """Everything an object scheduled for itself, gone with the object."""
268 return unschedule(object_id, None, base_dir=base_dir)
269
270
271def helpers(object_id: str, module: Any, base_dir: Path | str) -> tuple[Callable, Callable]:
272 """The ``_schedule``/``_unschedule`` pair injected into a system object.
273
274 A method name the module does not define is refused at schedule time:
275 the module is right here, so the check is free.
276 """
277
278 def _schedule(interval_seconds, method_name):
279 if isinstance(method_name, str) and not callable(getattr(module, method_name, None)):
280 raise ScheduleError(f"object {object_id} has no function {method_name!r} to schedule")
281 return schedule(object_id, method_name, interval_seconds, base_dir=base_dir)
282
283 def _unschedule(method_name=None):
284 return unschedule(object_id, method_name, base_dir=base_dir)
285
286 return _schedule, _unschedule