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

0 downloads

dbbasic-object-server/object_state.py
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.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_state.py · 5.0 KB · 154 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 time
15from collections.abc import Iterable
16from pathlib import Path
17from typing import Any
18
19from object_namespace import validate_object_id
20from object_versions import DEFAULT_DATA_DIR, InvalidObjectIdError
21
22STATE_FILE = "state.tsv"
23
24
25class ObjectStateManager:
26 """Runtime-owned object state manager."""
27
28 def __init__(self, object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR):
29 self.object_id = object_id
30 self.base_dir = Path(base_dir)
31 self.state_file = object_state_file(object_id, base_dir)
32 self.state_file.parent.mkdir(parents=True, exist_ok=True)
33 self._state = get_object_state(object_id, base_dir)
34
35 def get(self, key: str, default: Any = None) -> Any:
36 """Return one state value."""
37 return self._state.get(key, default)
38
39 def set(self, key: str, value: Any) -> None:
40 """Set one state value and persist the object state file."""
41 _validate_state_key(key)
42 self._state = get_object_state(self.object_id, self.base_dir)
43 self._state[key] = value
44 _write_object_state(self.state_file, self._state, timestamp=time.time())
45
46 def delete(self, key: str) -> None:
47 """Delete one state value and persist the object state file."""
48 _validate_state_key(key)
49 self._state = get_object_state(self.object_id, self.base_dir)
50 if key in self._state:
51 del self._state[key]
52 _write_object_state(self.state_file, self._state, timestamp=time.time())
53
54 def delete_many(self, keys: Iterable[str]) -> int:
55 """Delete state values in one atomic rewrite and return the removed count."""
56 clean_keys = list(dict.fromkeys(keys))
57 for key in clean_keys:
58 _validate_state_key(key)
59
60 self._state = get_object_state(self.object_id, self.base_dir)
61 removed = 0
62 for key in clean_keys:
63 if key in self._state:
64 del self._state[key]
65 removed += 1
66
67 if removed:
68 _write_object_state(self.state_file, self._state, timestamp=time.time())
69
70 return removed
71
72 def get_all(self) -> dict[str, Any]:
73 """Return all loaded state values."""
74 return dict(self._state)
75
76 def reload(self) -> None:
77 """Reload state from disk."""
78 self._state = get_object_state(self.object_id, self.base_dir)
79
80
81def get_object_state(object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, Any]:
82 """Return object state from ``data/state/{object_id}/state.tsv``."""
83 state_file = object_state_file(object_id, base_dir)
84 if not state_file.exists() or not state_file.is_file():
85 return {}
86
87 state: dict[str, Any] = {}
88 with state_file.open("r") as f:
89 for line in f:
90 row = _parse_state_row(line)
91 if row is None:
92 continue
93 key, value = row
94 state[key] = _coerce_value(value)
95
96 return state
97
98
99def object_state_file(object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
100 """Return a validated object state file path."""
101 if not validate_object_id(object_id):
102 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
103
104 state_root = Path(base_dir) / "state"
105 state_dir = state_root / object_id
106 resolved_root = state_root.resolve(strict=False)
107 resolved_dir = state_dir.resolve(strict=False)
108
109 try:
110 resolved_dir.relative_to(resolved_root)
111 except ValueError as exc:
112 raise InvalidObjectIdError(f"Object ID escapes state directory: {object_id}") from exc
113
114 return state_dir / STATE_FILE
115
116
117def _parse_state_row(line: str) -> tuple[str, str] | None:
118 stripped = line.strip()
119 if not stripped:
120 return None
121
122 parts = stripped.split("\t")
123 if parts[0] == "key" or len(parts) < 2:
124 return None
125
126 return parts[0], parts[1]
127
128
129def _write_object_state(state_file: Path, state: dict[str, Any], timestamp: float) -> None:
130 state_file.parent.mkdir(parents=True, exist_ok=True)
131 temp_path = state_file.with_name(f".{state_file.name}.tmp")
132
133 with temp_path.open("w") as f:
134 for key, value in sorted(state.items()):
135 f.write(f"{key}\t{value}\t{timestamp}\n")
136
137 temp_path.replace(state_file)
138
139
140def _validate_state_key(key: str) -> None:
141 if not isinstance(key, str) or not key:
142 raise ValueError("State key must be a non-empty string")
143 if any(char in key for char in "\t\r\n"):
144 raise ValueError(f"Invalid state key: {key!r}")
145
146
147def _coerce_value(value: str) -> Any:
148 try:
149 return int(value)
150 except ValueError:
151 try:
152 return float(value)
153 except ValueError:
154 return value