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_state.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_state.py · 11.3 KB · 295 lines
1"""Object state storage.
2
3The working prototype stores object state in plain TSV files:
4
5data/state/{object_id}/state.tsv
6
7Rows are either ``key<TAB>value`` or ``key<TAB>value<TAB>timestamp``. The
8timestamp column is ignored by read-only callers; it exists for replication and
9conflict handling in the full runtime.
10"""
11
12from __future__ import annotations
13
14import threading
15import time
16from collections.abc import Callable, Iterable, Mapping
17from contextlib import contextmanager
18from pathlib import Path
19from typing import Any
20
21try: # POSIX only; elsewhere the in-process lock still serialises threads
22 import fcntl
23except ImportError: # pragma: no cover
24 fcntl = None
25
26import object_user_quotas
27from object_namespace import validate_object_id
28from object_versions import DEFAULT_DATA_DIR, InvalidObjectIdError
29
30STATE_FILE = "state.tsv"
31
32# Writers of one state file take a per-file thread lock plus an flock on
33# ``state.tsv.lock`` (the cross-process half: pool workers, spawned children,
34# the daemon). The lock is re-entrant per thread so update()'s ``after_set``
35# callback may call back into the manager.
36_LOCKS_GUARD = threading.Lock()
37_THREAD_LOCKS: dict[str, threading.RLock] = {}
38_LOCK_DEPTH = threading.local()
39
40
41@contextmanager
42def _state_lock(state_file: Path):
43 key = str(state_file)
44 with _LOCKS_GUARD:
45 thread_lock = _THREAD_LOCKS.setdefault(key, threading.RLock())
46 depths = getattr(_LOCK_DEPTH, "depths", None)
47 if depths is None:
48 depths = _LOCK_DEPTH.depths = {}
49 with thread_lock:
50 depth = depths.get(key, 0)
51 lock_file = None
52 if depth == 0 and fcntl is not None:
53 state_file.parent.mkdir(parents=True, exist_ok=True)
54 lock_file = open(state_file.with_name(state_file.name + ".lock"), "a")
55 fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
56 depths[key] = depth + 1
57 try:
58 yield
59 finally:
60 depths[key] = depth
61 if lock_file is not None:
62 try:
63 fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
64 finally:
65 lock_file.close()
66
67
68class ObjectStateManager:
69 """Runtime-owned object state manager."""
70
71 def __init__(self, object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR, *, load: bool = True):
72 self.object_id = object_id
73 self.base_dir = Path(base_dir)
74 self.state_file = object_state_file(object_id, base_dir)
75 self.state_file.parent.mkdir(parents=True, exist_ok=True)
76 # load=False is for a writer that goes straight to update(), which
77 # reads the file itself under the lock: parsing here too would be wasted.
78 self._state = get_object_state(object_id, base_dir) if load else {}
79
80 def get(self, key: str, default: Any = None) -> Any:
81 """Return one state value."""
82 return self._state.get(key, default)
83
84 def set(self, key: str, value: Any) -> None:
85 """Set one state value and persist the object state file."""
86 _validate_state_key(key)
87 with _state_lock(self.state_file):
88 self._state = get_object_state(self.object_id, self.base_dir)
89 self._state[key] = value
90 _write_object_state(self.state_file, self._state, timestamp=time.time())
91
92 def increment(self, key: str, delta: int | float = 1) -> int | float:
93 """Atomically add ``delta`` to a numeric value and return the new value.
94
95 A missing key starts at 0. The read-modify-write happens under the
96 state file's lock, reloading from disk first, so concurrent threads
97 and processes never lose an update. A non-numeric existing value
98 raises TypeError and is left untouched.
99 """
100 _validate_state_key(key)
101 if isinstance(delta, bool) or not isinstance(delta, (int, float)):
102 raise TypeError("increment delta must be a number")
103 with _state_lock(self.state_file):
104 self._state = get_object_state(self.object_id, self.base_dir)
105 current = self._state.get(key, 0)
106 if isinstance(current, bool) or not isinstance(current, (int, float)):
107 raise TypeError(f"State value for {key!r} is not numeric")
108 new_value = current + delta
109 self._state[key] = new_value
110 _write_object_state(self.state_file, self._state, timestamp=time.time())
111 return new_value
112
113 def delete(self, key: str) -> None:
114 """Delete one state value and persist the object state file."""
115 _validate_state_key(key)
116 with _state_lock(self.state_file):
117 self._state = get_object_state(self.object_id, self.base_dir)
118 if key in self._state:
119 del self._state[key]
120 _write_object_state(self.state_file, self._state, timestamp=time.time())
121
122 def delete_many(self, keys: Iterable[str]) -> int:
123 """Delete state values in one atomic rewrite and return the removed count."""
124 clean_keys = list(dict.fromkeys(keys))
125 for key in clean_keys:
126 _validate_state_key(key)
127
128 with _state_lock(self.state_file):
129 self._state = get_object_state(self.object_id, self.base_dir)
130 removed = 0
131 for key in clean_keys:
132 if key in self._state:
133 del self._state[key]
134 removed += 1
135
136 if removed:
137 _write_object_state(self.state_file, self._state, timestamp=time.time())
138
139 return removed
140
141 def update(
142 self,
143 set_items: Mapping[str, Any],
144 *,
145 after_set: Callable[[dict[str, Any]], Iterable[str]] | None = None,
146 ) -> int:
147 """Set several keys, then optionally delete others, in ONE rewrite.
148
149 set()/delete_many() each re-read the whole file and rewrite it, so
150 "set this, then delete whatever the result says to drop" costs two
151 full parses and two full rewrites of a file that may be a thousand
152 rows long. This re-reads the file once under the state lock, applies
153 both steps and writes once, so a concurrent set()/increment()/update()
154 is never lost and the file is never visible half-done. Build the
155 manager with load=False when update() is the only call, to parse once.
156
157 `after_set(state)` is called with the state AFTER `set_items` were
158 applied and returns the keys to delete; it must not mutate `state`.
159 Returns how many keys were deleted.
160 """
161 clean = {}
162 for key, value in set_items.items():
163 _validate_state_key(key)
164 clean[key] = value
165 with _state_lock(self.state_file):
166 self._state = get_object_state(self.object_id, self.base_dir)
167 self._state.update(clean)
168
169 removed = 0
170 if after_set is not None:
171 for key in dict.fromkeys(after_set(self._state)):
172 _validate_state_key(key)
173 if key in self._state:
174 del self._state[key]
175 removed += 1
176
177 _write_object_state(self.state_file, self._state, timestamp=time.time())
178 return removed
179
180 def modify(self, change: Callable[[dict[str, Any]], Any]) -> Any:
181 """Read, decide and write under ONE hold of the state lock.
182
183 For a writer whose decision depends on other keys -- "add this row
184 unless the owner already has ten", "write the run bookkeeping back
185 unless the row was deleted meanwhile" -- set()/update() cannot help:
186 the read they would decide from is not inside their lock. `change`
187 gets a fresh copy of the state, mutates it in place and returns
188 anything; the file is rewritten only when the copy differs.
189 """
190 with _state_lock(self.state_file):
191 current = get_object_state(self.object_id, self.base_dir)
192 working = dict(current)
193 result = change(working)
194 if working != current:
195 for key in working:
196 _validate_state_key(key)
197 _write_object_state(self.state_file, working, timestamp=time.time())
198 self._state = working
199 return result
200
201 def get_all(self) -> dict[str, Any]:
202 """Return all loaded state values."""
203 return dict(self._state)
204
205 def reload(self) -> None:
206 """Reload state from disk."""
207 self._state = get_object_state(self.object_id, self.base_dir)
208
209
210def get_object_state(object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, Any]:
211 """Return object state from ``data/state/{object_id}/state.tsv``."""
212 state_file = object_state_file(object_id, base_dir)
213 if not state_file.exists() or not state_file.is_file():
214 return {}
215
216 state: dict[str, Any] = {}
217 with state_file.open("r") as f:
218 for line in f:
219 row = _parse_state_row(line)
220 if row is None:
221 continue
222 key, value = row
223 state[key] = _coerce_value(value)
224
225 return state
226
227
228def object_state_file(object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
229 """Return a validated object state file path."""
230 if not validate_object_id(object_id):
231 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
232
233 state_root = Path(base_dir) / "state"
234 state_dir = state_root / object_id
235 resolved_root = state_root.resolve(strict=False)
236 resolved_dir = state_dir.resolve(strict=False)
237
238 try:
239 resolved_dir.relative_to(resolved_root)
240 except ValueError as exc:
241 raise InvalidObjectIdError(f"Object ID escapes state directory: {object_id}") from exc
242
243 return state_dir / STATE_FILE
244
245
246def _parse_state_row(line: str) -> tuple[str, str] | None:
247 stripped = line.strip()
248 if not stripped:
249 return None
250
251 parts = stripped.split("\t")
252 if parts[0] == "key" or len(parts) < 2:
253 return None
254
255 return parts[0], parts[1]
256
257
258def _write_object_state(state_file: Path, state: dict[str, Any], timestamp: float) -> None:
259 state_file.parent.mkdir(parents=True, exist_ok=True)
260 temp_path = state_file.with_name(f".{state_file.name}.tmp")
261
262 text = "".join(f"{key}\t{value}\t{timestamp}\n" for key, value in sorted(state.items()))
263 # The one place every state write ends up (helpers, the sandbox proxy,
264 # the daemon): a user object's file may not outgrow its quota.
265 previous = state_file.stat().st_size if state_file.exists() else 0
266 object_user_quotas.check_state_size(
267 state_file.parent.name, len(text.encode("utf-8")), previous
268 )
269 with temp_path.open("w") as f:
270 f.write(text)
271
272 temp_path.replace(state_file)
273
274
275def _validate_state_key(key: str) -> None:
276 if not isinstance(key, str) or not key:
277 raise ValueError("State key must be a non-empty string")
278 if any(char in key for char in "\t\r\n"):
279 raise ValueError(f"Invalid state key: {key!r}")
280
281
282def _coerce_value(value: str) -> Any:
283 # A JSON object, array or string can never parse as a number. Most state
284 # values in a busy system are exactly that (the events log is one JSON
285 # object per row), and for them the two attempts below were two raised
286 # and caught exceptions per row, on every read of the whole file.
287 if value[:1] in ("{", "[", '"'):
288 return value
289 try:
290 return int(value)
291 except ValueError:
292 try:
293 return float(value)
294 except ValueError:
295 return value