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/scripts/migrate_from_object_primitive.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, 18 minutes ago History
migrate_from_object_primitive.py · 17.6 KB · 417 lines
1#!/usr/bin/env python3
2"""Copy objects from the OLD askrobots object server into this one.
3
4Read-only against the old server (HTTP GET only), offline write into the new
5server's objects dir + data dir. See docs/migrating-from-object-primitive.md.
6
7 DBBASIC_OLD_AUTH='Basic <b64>' python scripts/migrate_from_object_primitive.py \
8 --old-url http://old:8001 --auth-env DBBASIC_OLD_AUTH \
9 --objects-dir ./objects --data-dir ./data # dry run
10 ... --apply # write + verify
11
12The auth header VALUE is read from an environment variable or a file and is
13never accepted on the command line and never printed.
14"""
15from __future__ import annotations
16
17import argparse
18import fnmatch
19import hashlib
20import json
21import os
22import re
23import sys
24import time
25import urllib.error
26import urllib.parse
27import urllib.request
28from pathlib import Path
29
30sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
31
32import csv # noqa: E402
33
34import object_namespace # noqa: E402
35import object_state # noqa: E402
36import object_versions # noqa: E402
37
38
39class FetchError(Exception):
40 pass
41
42
43class RateLimited(FetchError):
44 """The old server kept answering HTTP 429 past the wait budget."""
45
46
47DEFAULT_RATE_LIMIT_WAIT = 300.0 # seconds one run may spend waiting out 429s
48RATE_LIMIT_FALLBACK_WAIT = 5.0 # a 429 that does not say how long to wait
49_TRY_AGAIN = re.compile(r"try again in (\d+(?:\.\d+)?) seconds?", re.IGNORECASE)
50
51
52def rate_limit_delay(retry_after: str | None, body: str) -> float:
53 """Seconds a 429 asks us to wait: the Retry-After header (seconds form),
54 else the old server's "Try again in N seconds." text, else a short default."""
55 text = (retry_after or "").strip()
56 if re.fullmatch(r"\d+(?:\.\d+)?", text):
57 return float(text)
58 found = _TRY_AGAIN.search(body or "")
59 if found:
60 return float(found.group(1))
61 return RATE_LIMIT_FALLBACK_WAIT
62
63
64def sha(text: str) -> str:
65 return hashlib.sha256(text.encode()).hexdigest()
66
67
68# ---------------------------------------------------------------- old server
69
70class OldServer:
71 def __init__(self, base_url: str, auth_header: str | None, timeout: float = 30,
72 rate_limit_wait: float = DEFAULT_RATE_LIMIT_WAIT, sleep=None, notify=None):
73 self.base = base_url.rstrip("/")
74 self.auth = auth_header
75 self.timeout = timeout
76 self.wait_left = max(0.0, rate_limit_wait) # shared by the whole run
77 self.waited = 0.0
78 self.sleep = sleep or (lambda seconds: time.sleep(seconds))
79 self.notify = notify or (lambda message: None)
80
81 def get(self, path: str, **query) -> dict:
82 """GET and decode JSON. An HTTP 429 is waited out (for as long as the
83 answer says, plus a second) and retried until the run's wait budget is
84 spent; then RateLimited is raised. A 429 is never an answer."""
85 url = f"{self.base}{path}"
86 if query:
87 url += "?" + urllib.parse.urlencode(query)
88 while True:
89 req = urllib.request.Request(url, method="GET")
90 if self.auth:
91 req.add_header("Authorization", self.auth)
92 try:
93 with urllib.request.urlopen(req, timeout=self.timeout) as resp:
94 return json.loads(resp.read().decode())
95 except urllib.error.HTTPError as exc:
96 body = ""
97 try:
98 body = exc.read().decode(errors="replace")
99 except Exception:
100 pass
101 if exc.code == 429:
102 delay = rate_limit_delay(exc.headers.get("Retry-After") if exc.headers else None, body) + 1.0
103 if delay > self.wait_left:
104 raise RateLimited(
105 f"GET {path} -> HTTP 429: rate limited by the old server; it asked for "
106 f"{delay:.0f}s and {self.wait_left:.0f}s of the wait budget is left") from None
107 self.notify(f"rate limited by the old server (HTTP 429); waiting {delay:.0f}s")
108 self.wait_left -= delay
109 self.waited += delay
110 self.sleep(delay)
111 continue
112 detail = ""
113 try:
114 detail = str(json.loads(body).get("error", "")).splitlines()[0][:160]
115 except Exception:
116 pass
117 raise FetchError(f"GET {path} -> HTTP {exc.code}" + (f": {detail}" if detail else "")) from None
118 except (urllib.error.URLError, OSError, ValueError) as exc:
119 raise FetchError(f"GET {path} failed: {type(exc).__name__}") from None
120
121 def list_objects(self) -> list[dict]:
122 return self.get("/objects", format="json").get("objects", [])
123
124 def fetch(self, object_id: str) -> dict:
125 """Everything about one object: source, state, versions with content."""
126 p = f"/objects/{object_id}"
127 source = self.get(p, source="true", format="json")["source"]
128 state = self.get(p, state="true").get("state", {})
129 hist = self.get(p, versions="true", limit=100000).get("versions", [])
130 versions = []
131 for meta in sorted(hist, key=lambda v: v["version_id"]):
132 full = self.get(p, version=meta["version_id"]).get("version", {})
133 versions.append({
134 "version_id": meta["version_id"],
135 "timestamp": meta.get("timestamp", ""),
136 "author": meta.get("author", ""),
137 "message": meta.get("message", ""),
138 "content": full.get("content", ""),
139 })
140 return {"source": source, "state": state, "versions": versions}
141
142
143# ---------------------------------------------------------------- state text
144
145def encode_state_value(value) -> str:
146 """Text this server's state.tsv stores for an old JSON value."""
147 if isinstance(value, (dict, list, bool)) or value is None:
148 return json.dumps(value)
149 return str(value)
150
151
152def state_problem(key: str, text: str) -> str | None:
153 if not key or any(c in key for c in "\t\r\n"):
154 return f"state key {key!r} is not storable"
155 if any(c in text for c in "\t\r\n"):
156 return f"state value for {key!r} contains a tab/newline (state.tsv cannot hold it)"
157 return None
158
159
160def expected_state(state: dict) -> dict:
161 """What this server will read back after we store `state`."""
162 return {k: object_state._coerce_value(encode_state_value(v)) for k, v in state.items()}
163
164
165# ---------------------------------------------------------------- target
166
167class Target:
168 def __init__(self, objects_dir: Path, data_dir: Path):
169 self.objects = Path(objects_dir)
170 self.data = Path(data_dir)
171
172 def source_path(self, object_id: str) -> Path:
173 if not object_namespace.validate_object_id(object_id):
174 raise ValueError(f"invalid object id {object_id!r}")
175 parsed = object_namespace.parse_user_object_id(object_id)
176 if parsed:
177 p = self.objects / "users" / str(parsed[0]) / f"{parsed[1]}.py"
178 elif "_" in object_id:
179 cat, name = object_id.split("_", 1)
180 p = self.objects / cat / f"{name}.py"
181 else:
182 p = self.objects / f"{object_id}.py"
183 if object_namespace.object_id_from_path(p, self.objects) != object_id:
184 raise ValueError(f"object id {object_id!r} does not round-trip to a path")
185 return p
186
187 def existing_source(self, object_id: str) -> tuple[Path, str] | None:
188 found = object_namespace.resolve_object_id(object_id, roots=[self.objects])
189 if found is None:
190 return None
191 return Path(found), Path(found).read_text()
192
193 def state(self, object_id: str) -> dict:
194 return object_state.get_object_state(object_id, base_dir=self.data)
195
196 def versions(self, object_id: str) -> list[dict]:
197 mgr = object_versions.VersionManager(self.data)
198 out = []
199 for v in reversed(mgr.get_history(object_id)):
200 full = mgr.get_version(object_id, v["version_id"]) or v
201 out.append(full)
202 return out
203
204
205def write_versions(target: Target, object_id: str, versions: list[dict], replace: bool) -> None:
206 mgr = object_versions.VersionManager(target.data)
207 d = mgr._object_dir(object_id, create=True)
208 if replace:
209 for f in d.glob("v*.txt"):
210 f.unlink()
211 meta = d / object_versions.METADATA_FILE
212 if meta.exists():
213 meta.unlink()
214 with (d / object_versions.METADATA_FILE).open("w", newline="") as f:
215 w = csv.DictWriter(f, fieldnames=object_versions.METADATA_FIELDS, delimiter="\t")
216 w.writeheader()
217 for v in versions:
218 (d / f"v{v['version_id']}.txt").write_text(v["content"])
219 w.writerow({
220 "version_id": v["version_id"], "timestamp": v["timestamp"],
221 "author": v["author"], "message": v["message"],
222 "hash": mgr._compute_hash(v["content"]), "correlation_id": "",
223 })
224
225
226def write_source(path: Path, text: str) -> None:
227 path.parent.mkdir(parents=True, exist_ok=True)
228 tmp = path.with_name(f".{path.name}.tmp")
229 tmp.write_text(text)
230 tmp.replace(path)
231
232
233# ---------------------------------------------------------------- planning
234
235def select(entries: list[dict], only: list[str], exclude: list[str]) -> list[dict]:
236 def hit(e, pats):
237 return any(fnmatch.fnmatch(e["object_id"], p) or fnmatch.fnmatch(e.get("path", ""), p) for p in pats)
238 return [e for e in entries if (not only or hit(e, only)) and not (exclude and hit(e, exclude))]
239
240
241def plan_object(old: dict, target: Target, object_id: str, overwrite: bool) -> dict:
242 """Classify one object: create | identical | fill | conflict | error."""
243 item = {"object_id": object_id, "state_keys": len(old["state"]),
244 "versions": len(old["versions"]), "notes": []}
245 try:
246 target.source_path(object_id)
247 except ValueError as exc:
248 return {**item, "action": "error", "reason": str(exc)}
249 for k, v in old["state"].items():
250 prob = state_problem(k, encode_state_value(v))
251 if prob:
252 return {**item, "action": "error", "reason": prob}
253 if isinstance(v, str) and expected_state({k: v})[k] != v:
254 item["notes"].append(f"state {k!r}: string {v!r} reads back as a number here")
255 if isinstance(v, (bool, dict, list)) or v is None:
256 item["notes"].append(f"state {k!r}: {type(v).__name__} stored as JSON text")
257 existing = target.existing_source(object_id)
258 if existing is None:
259 return {**item, "action": "create"}
260 _, tsrc = existing
261 tstate, tvers = target.state(object_id), target.versions(object_id)
262 same_src = sha(tsrc) == sha(old["source"])
263 want_state = expected_state(old["state"])
264 state_ok = tstate == want_state
265 old_hashes = [sha(v["content"]) for v in old["versions"]]
266 t_hashes = [sha(v["content"]) for v in tvers]
267 vers_ok = t_hashes == old_hashes
268 if same_src and state_ok and vers_ok:
269 return {**item, "action": "identical"}
270 conflicts = []
271 if not same_src:
272 conflicts.append("source differs")
273 if tstate and not state_ok:
274 conflicts.append("state differs")
275 if tvers and not vers_ok:
276 conflicts.append("versions differ")
277 if conflicts:
278 return {**item, "action": "overwrite" if overwrite else "conflict", "reason": ", ".join(conflicts)}
279 return {**item, "action": "fill", "reason": "source identical; filling missing state/versions"}
280
281
282def apply_object(old: dict, target: Target, object_id: str, action: str) -> None:
283 replace = action == "overwrite"
284 existing = target.existing_source(object_id)
285 write_source(existing[0] if existing else target.source_path(object_id), old["source"])
286 new_state = {k: encode_state_value(v) for k, v in old["state"].items()}
287 mgr = object_state.ObjectStateManager(object_id, target.data, load=False)
288 if new_state or replace:
289 mgr.update(new_state, after_set=(lambda s: [k for k in s if k not in new_state]) if replace else None)
290 if old["versions"]:
291 write_versions(target, object_id, old["versions"], replace=True)
292
293
294def verify_object(server: OldServer, target: Target, object_id: str) -> list[str]:
295 old = server.fetch(object_id)
296 problems = []
297 ex = target.existing_source(object_id)
298 if ex is None:
299 return ["missing in target"]
300 if sha(ex[1]) != sha(old["source"]):
301 problems.append("source hash differs")
302 if target.state(object_id) != expected_state(old["state"]):
303 problems.append("state differs")
304 got = [(v["version_id"], sha(v["content"]), v["author"], v["message"], v["timestamp"]) for v in target.versions(object_id)]
305 want = [(v["version_id"], sha(v["content"]), v["author"], v["message"], v["timestamp"]) for v in old["versions"]]
306 if got != want:
307 problems.append("versions differ")
308 return problems
309
310
311# ---------------------------------------------------------------- main
312
313def read_auth(args) -> str | None:
314 if args.auth_env:
315 val = os.environ.get(args.auth_env)
316 if not val:
317 raise SystemExit(f"environment variable {args.auth_env} is empty or unset")
318 return val.strip()
319 if args.auth_file:
320 return Path(args.auth_file).read_text().strip()
321 return None
322
323
324def main(argv=None, out=print) -> int:
325 ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
326 ap.add_argument("--old-url", required=True)
327 ap.add_argument("--auth-env", help="env var holding the full Authorization header value")
328 ap.add_argument("--auth-file", help="file holding the full Authorization header value")
329 ap.add_argument("--objects-dir", required=True)
330 ap.add_argument("--data-dir", required=True)
331 ap.add_argument("--apply", action="store_true", help="write (default is a dry run)")
332 ap.add_argument("--overwrite", action="store_true", help="replace conflicting target objects")
333 ap.add_argument("--only", action="append", default=[], metavar="GLOB")
334 ap.add_argument("--exclude", action="append", default=[], metavar="GLOB")
335 ap.add_argument("--report", default="migration-report.json")
336 ap.add_argument("--rate-limit-wait", type=float, default=DEFAULT_RATE_LIMIT_WAIT, metavar="SECONDS",
337 help="most seconds one run spends waiting when the old server answers "
338 "HTTP 429 (default %(default)s; 0 = do not wait)")
339 args = ap.parse_args(argv)
340
341 server = OldServer(args.old_url, read_auth(args), rate_limit_wait=args.rate_limit_wait,
342 notify=lambda message: out(f" {message}"))
343 target = Target(Path(args.objects_dir), Path(args.data_dir))
344 try:
345 entries = select(server.list_objects(), args.only, args.exclude)
346 except FetchError as exc:
347 out(f"error: {exc}")
348 return 2
349 out(f"{'APPLY' if args.apply else 'DRY RUN'}: {len(entries)} object(s) selected")
350
351 plan, fetched = [], {}
352 for e in entries:
353 oid = e["object_id"]
354 try:
355 fetched[oid] = server.fetch(oid)
356 except (FetchError, KeyError) as exc:
357 plan.append({"object_id": oid, "action": "error", "reason": f"fetch failed: {exc}",
358 "state_keys": 0, "versions": 0, "notes": []})
359 continue
360 item = plan_object(fetched[oid], target, oid, args.overwrite)
361 item["path"] = e.get("path")
362 item["owner"] = e.get("owner")
363 plan.append(item)
364 for p in plan:
365 extra = f" ({p['reason']})" if p.get("reason") else ""
366 out(f" {p['action']:<9} {p['object_id']} state_keys={p['state_keys']} versions={p['versions']}{extra}")
367 for n in p["notes"]:
368 out(f" note: {n}")
369
370 counts: dict[str, int] = {}
371 for p in plan:
372 counts[p["action"]] = counts.get(p["action"], 0) + 1
373 out("summary: " + ", ".join(f"{k}={v}" for k, v in sorted(counts.items())))
374
375 report = {"apply": args.apply, "old_url": args.old_url, "plan": plan, "verify": None,
376 "unverified": None}
377 rc = 0
378 if args.apply:
379 for p in plan:
380 if p["action"] in ("create", "fill", "overwrite"):
381 apply_object(fetched[p["object_id"]], target, p["object_id"], p["action"])
382 out("verifying ...")
383 # An object the old server would not let us re-read was not compared:
384 # it is neither a match nor a mismatch, and is counted on its own.
385 results, unverified = {}, {}
386 for p in plan:
387 if p["action"] in ("create", "fill", "overwrite", "identical"):
388 try:
389 results[p["object_id"]] = verify_object(server, target, p["object_id"])
390 except (FetchError, KeyError) as exc:
391 unverified[p["object_id"]] = f"verify fetch failed: {exc}"
392 bad = {k: v for k, v in results.items() if v}
393 out(f"verified {len(results)} object(s): {len(results) - len(bad)} match, {len(bad)} mismatch, "
394 f"{len(unverified)} could not verify")
395 for k, v in bad.items():
396 out(f" MISMATCH {k}: {'; '.join(v)}")
397 for k, v in unverified.items():
398 out(f" COULD NOT VERIFY {k}: {v}")
399 if unverified:
400 out(" the objects above were written but not compared; run the same command again to verify them")
401 report["verify"] = results
402 report["unverified"] = unverified
403 if bad:
404 rc = 1
405 elif unverified:
406 rc = 3
407 if counts.get("error"):
408 rc = 1
409 if server.waited:
410 out(f"waited {server.waited:.0f}s in total for the old server's rate limit")
411 Path(args.report).write_text(json.dumps(report, indent=2))
412 out(f"report written to {args.report}")
413 return rc
414
415
416if __name__ == "__main__":
417 sys.exit(main())