offgit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
offgit/server/cli.py ADDED
@@ -0,0 +1,391 @@
1
+ """``offgit-server``: RPC entry point (forced SSH command) and admin commands.
2
+
3
+ Admin commands are run by an administrator on the server, as the service user:
4
+ ``sudo -u offgit /opt/offgit/venv/bin/offgit-server <command>``. They are never
5
+ reachable through the restricted RPC key.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+ from typing import Annotated, Any
15
+
16
+ import typer
17
+
18
+ from offgit import __version__
19
+
20
+ app = typer.Typer(
21
+ add_completion=False,
22
+ no_args_is_help=True,
23
+ rich_markup_mode=None,
24
+ pretty_exceptions_enable=False,
25
+ context_settings={"help_option_names": ["-h", "--help"]},
26
+ help="offgit server: SSH-launched RPC and administration of the authoritative store.",
27
+ )
28
+
29
+ JsonOpt = Annotated[bool, typer.Option("--json", help="Machine-readable output.")]
30
+ ConfigOpt = Annotated[
31
+ str | None, typer.Option("--config", help="Server config (default /etc/offgit/server.toml).")
32
+ ]
33
+
34
+
35
+ def _version_cb(value: bool) -> None:
36
+ if value:
37
+ typer.echo(f"offgit-server {__version__}")
38
+ raise typer.Exit(0)
39
+
40
+
41
+ @app.callback()
42
+ def _main(
43
+ version: Annotated[
44
+ bool, typer.Option("--version", callback=_version_cb, is_eager=True, help="Show version.")
45
+ ] = False,
46
+ ) -> None:
47
+ os.umask(0o077)
48
+
49
+
50
+ def _settings(config: str | None): # type: ignore[no-untyped-def]
51
+ from offgit.server.settings import SettingsError, load_settings
52
+
53
+ try:
54
+ return load_settings(config)
55
+ except SettingsError as exc:
56
+ _fail(f"configuration error: {exc}", 2)
57
+
58
+
59
+ def _fail(msg: str, code: int = 1) -> None:
60
+ typer.echo(f"offgit-server: error: {msg}", err=True)
61
+ raise typer.Exit(code)
62
+
63
+
64
+ def _emit(data: Any, json_out: bool, human: str) -> None:
65
+ if json_out:
66
+ typer.echo(json.dumps(data, indent=2, sort_keys=True))
67
+ else:
68
+ typer.echo(human)
69
+
70
+
71
+ @app.command()
72
+ def rpc() -> None:
73
+ """Serve one RPC request on stdin/stdout (used as the SSH forced command)."""
74
+ from offgit.server.rpc import serve
75
+
76
+ raise typer.Exit(serve())
77
+
78
+
79
+ @app.command("init-store")
80
+ def init_store(config: ConfigOpt = None, json_out: JsonOpt = False) -> None:
81
+ """Create the empty authoritative store (refuses to overwrite)."""
82
+ from offgit.server.schema import StoreError
83
+ from offgit.server.schema import init_store as _init
84
+
85
+ s = _settings(config)
86
+ s.data_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
87
+ s.locks_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
88
+ try:
89
+ server_id, epoch = _init(s.store_path)
90
+ except StoreError as exc:
91
+ _fail(exc.message, 2)
92
+ _emit(
93
+ {"store": str(s.store_path), "server_id": server_id, "server_epoch": epoch},
94
+ json_out,
95
+ f"Created {s.store_path}\nserver id {server_id}\nepoch {epoch}",
96
+ )
97
+
98
+
99
+ @app.command()
100
+ def verify(config: ConfigOpt = None, json_out: JsonOpt = False) -> None:
101
+ """Full consistency check of the live store (integrity, FKs, blobs, manifests)."""
102
+ from offgit.server.locks import flock
103
+ from offgit.server.schema import StoreError, connect, verify_connection
104
+
105
+ s = _settings(config)
106
+ if not s.store_path.exists():
107
+ _fail("store does not exist", 2)
108
+ try:
109
+ with flock(
110
+ s.locks_dir / "maintenance.lock", exclusive=False, timeout=s.lock_timeout_seconds
111
+ ):
112
+ conn = connect(s.store_path, busy_timeout_ms=s.busy_timeout_ms)
113
+ try:
114
+ rep = verify_connection(conn)
115
+ finally:
116
+ conn.close()
117
+ except StoreError as exc:
118
+ _fail(exc.message)
119
+ d = rep.to_dict()
120
+ human = (
121
+ f"{'OK' if rep.ok else 'FAILED'}: {rep.projects} projects, {rep.revisions} revisions, "
122
+ f"{rep.blobs} blobs ({rep.blob_bytes} bytes), schema {rep.schema_version}"
123
+ )
124
+ if rep.problems:
125
+ human += "\n" + "\n".join(f" - {p}" for p in rep.problems)
126
+ _emit(d, json_out, human)
127
+ raise typer.Exit(0 if rep.ok else 1)
128
+
129
+
130
+ @app.command()
131
+ def info(config: ConfigOpt = None, json_out: JsonOpt = False) -> None:
132
+ """Diagnostics: paths, identity, usage, limits, backup health."""
133
+ from offgit.server.health import health_summary, read_health
134
+ from offgit.server.schema import StoreError
135
+ from offgit.server.store import Store
136
+
137
+ s = _settings(config)
138
+ data: dict[str, Any] = {
139
+ "version": __version__,
140
+ "config": str(s.config_path) if s.config_path else None,
141
+ "data_dir": str(s.data_dir),
142
+ "store": str(s.store_path),
143
+ "limits": s.limits,
144
+ "backup_repository": s.backup.repository,
145
+ }
146
+ try:
147
+ store = Store(s)
148
+ try:
149
+ data.update({"server_id": store.server_id, "server_epoch": store.server_epoch})
150
+ data["usage"] = store.usage()
151
+ finally:
152
+ store.close()
153
+ except StoreError as exc:
154
+ data["store_error"] = exc.message
155
+ health = read_health(s.health_path)
156
+ data["backup"] = health_summary(s.health_path)
157
+ if health.get("last_error"):
158
+ data["backup"]["last_error"] = health["last_error"]
159
+ if health.get("snapshot_id"):
160
+ data["backup"]["snapshot_id"] = health["snapshot_id"]
161
+ _emit(data, json_out, json.dumps(data, indent=2, sort_keys=True))
162
+
163
+
164
+ @app.command()
165
+ def projects(config: ConfigOpt = None, json_out: JsonOpt = False) -> None:
166
+ """List projects in the store."""
167
+ from offgit.server.store import Store
168
+
169
+ s = _settings(config)
170
+ store = Store(s)
171
+ try:
172
+ res = store.projects()
173
+ finally:
174
+ store.close()
175
+ lines = [
176
+ f"{p['revision']:>6} {p['files']:>4} files {p['bytes']:>9} B {p['canonical_remote']} {p['id'][:12]}"
177
+ for p in res["projects"]
178
+ ]
179
+ _emit(res, json_out, "\n".join(lines) or "(no projects)")
180
+
181
+
182
+ @app.command()
183
+ def export(
184
+ project: Annotated[str, typer.Option("--project", help="Project id or canonical identity.")],
185
+ destination: Annotated[Path, typer.Option("--destination", help="New, empty directory.")],
186
+ revision: Annotated[int | None, typer.Option("--revision")] = None,
187
+ config: ConfigOpt = None,
188
+ json_out: JsonOpt = False,
189
+ ) -> None:
190
+ """Export one project revision as manifest.json + files/ for inspection (read-only)."""
191
+ from offgit.server.export import ExportError, export_project
192
+ from offgit.server.store import Store
193
+
194
+ s = _settings(config)
195
+ store = Store(s)
196
+ try:
197
+ manifest = export_project(store, project, destination, revision)
198
+ except ExportError as exc:
199
+ _fail(str(exc), 2)
200
+ finally:
201
+ store.close()
202
+ _emit(
203
+ manifest,
204
+ json_out,
205
+ f"Exported {manifest['canonical_remote']} revision {manifest['revision']} to {destination}",
206
+ )
207
+
208
+
209
+ @app.command()
210
+ def snapshot(
211
+ destination: Annotated[Path, typer.Option("--destination", help="New, empty directory.")],
212
+ config: ConfigOpt = None,
213
+ json_out: JsonOpt = False,
214
+ ) -> None:
215
+ """Write a verified consistent snapshot (store.sqlite3 + manifest.json) without uploading."""
216
+ from offgit.server.backup import BackupError, create_snapshot
217
+
218
+ s = _settings(config)
219
+ try:
220
+ manifest = create_snapshot(s, destination)
221
+ except BackupError as exc:
222
+ _fail(str(exc))
223
+ _emit(
224
+ manifest,
225
+ json_out,
226
+ f"Snapshot written to {destination} (sha256 {manifest['db_sha256'][:16]}…)",
227
+ )
228
+
229
+
230
+ @app.command("backup-init")
231
+ def backup_init(
232
+ adopt_existing: Annotated[
233
+ bool,
234
+ typer.Option("--adopt-existing", help="Record an already-initialized restic repository."),
235
+ ] = False,
236
+ config: ConfigOpt = None,
237
+ json_out: JsonOpt = False,
238
+ ) -> None:
239
+ """One-time: create the restic password file (if absent) and init/adopt the repository."""
240
+ from offgit.server.backup import BackupError
241
+ from offgit.server.backup import backup_init as _bi
242
+ from offgit.server.locks import LockBusy
243
+
244
+ s = _settings(config)
245
+ try:
246
+ res = _bi(s, adopt_existing=adopt_existing)
247
+ except (BackupError, LockBusy) as exc:
248
+ _fail(str(exc))
249
+ human = f"Repository {s.backup.repository} recorded (id {res['repository_id'][:12]}…)"
250
+ if res["created_password_file"]:
251
+ human += (
252
+ f"\nA new restic password was generated in {res['password_file']} (not printed)."
253
+ "\nCopy it to a safe place OFF this server now; without it the backup is unrecoverable."
254
+ )
255
+ _emit(res, json_out, human)
256
+
257
+
258
+ @app.command()
259
+ def backup(config: ConfigOpt = None, json_out: JsonOpt = False) -> None:
260
+ """Snapshot, verify and upload an encrypted versioned backup with restic."""
261
+ from offgit.server.backup import BackupError, run_backup
262
+
263
+ s = _settings(config)
264
+ try:
265
+ res = run_backup(s)
266
+ except BackupError as exc:
267
+ _fail(str(exc))
268
+ _emit(
269
+ res,
270
+ json_out,
271
+ f"Backup ok: snapshot {res['snapshot_id']} ({res['manifest']['projects']} projects)",
272
+ )
273
+
274
+
275
+ @app.command("backup-status")
276
+ def backup_status(config: ConfigOpt = None, json_out: JsonOpt = False) -> None:
277
+ """Show the last backup attempt/success recorded on this server."""
278
+ from offgit.server.health import read_health
279
+
280
+ s = _settings(config)
281
+ h = read_health(s.health_path)
282
+ if not h:
283
+ _emit({}, json_out, "No backup has been attempted yet")
284
+ raise typer.Exit(1)
285
+ _emit(h, json_out, json.dumps(h, indent=2, sort_keys=True))
286
+ raise typer.Exit(0 if h.get("last_result") == "ok" else 1)
287
+
288
+
289
+ @app.command("backup-forget")
290
+ def backup_forget(
291
+ prune: Annotated[
292
+ bool, typer.Option("--prune", help="Also prune unreferenced data (slow).")
293
+ ] = False,
294
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Show what would be removed.")] = False,
295
+ config: ConfigOpt = None,
296
+ ) -> None:
297
+ """Apply the cloud retention policy (only after a successful backup)."""
298
+ from offgit.server.backup import BackupError, forget
299
+ from offgit.server.locks import LockBusy
300
+
301
+ s = _settings(config)
302
+ try:
303
+ out = forget(s, prune=prune, dry_run=dry_run)
304
+ except (BackupError, LockBusy) as exc:
305
+ _fail(str(exc))
306
+ typer.echo(out)
307
+
308
+
309
+ @app.command("backup-check")
310
+ def backup_check(
311
+ read_data_subset: Annotated[str | None, typer.Option("--read-data-subset")] = None,
312
+ config: ConfigOpt = None,
313
+ ) -> None:
314
+ """Run 'restic check' against the backup repository."""
315
+ from offgit.server.backup import BackupError, check
316
+ from offgit.server.locks import LockBusy
317
+
318
+ s = _settings(config)
319
+ try:
320
+ out = check(s, read_data_subset=read_data_subset)
321
+ except (BackupError, LockBusy) as exc:
322
+ _fail(str(exc))
323
+ typer.echo(out)
324
+
325
+
326
+ @app.command()
327
+ def restore(
328
+ source: Annotated[Path, typer.Option("--from", help="Validated restored backup directory.")],
329
+ yes: Annotated[bool, typer.Option("--yes", help="Confirm replacing the live store.")] = False,
330
+ new_server_id: Annotated[bool, typer.Option("--new-server-id")] = False,
331
+ config: ConfigOpt = None,
332
+ json_out: JsonOpt = False,
333
+ ) -> None:
334
+ """Validate a backup stage and atomically install it as the live store (new epoch)."""
335
+ from offgit.server.restore import RestoreError, locate_stage, restore_store, validate_stage
336
+
337
+ s = _settings(config)
338
+ try:
339
+ stage = locate_stage(source)
340
+ checked = validate_stage(stage)
341
+ except RestoreError as exc:
342
+ _fail(str(exc), 2)
343
+ m = checked["manifest"]
344
+ typer.echo(
345
+ f"Backup stage {stage}\n captured {m.get('captured_at')}, {m.get('projects')} projects, "
346
+ f"server {m.get('server_id')}",
347
+ err=True,
348
+ )
349
+ if not yes:
350
+ if not sys.stdin.isatty():
351
+ _fail("confirmation required: re-run with --yes", 2)
352
+ if not typer.confirm(
353
+ "Replace the live store with this backup? (a safety copy is kept)", err=True
354
+ ):
355
+ _fail("aborted", 2)
356
+ try:
357
+ res = restore_store(s, stage, new_server_id=new_server_id)
358
+ except RestoreError as exc:
359
+ _fail(str(exc))
360
+ _emit(
361
+ res,
362
+ json_out,
363
+ f"Restored. New server epoch {res['server_epoch']}.\n"
364
+ f"Previous store copy: {res['previous_store_copy']}\n"
365
+ "Every client must now run 'offgit rebaseline' in each worktree.",
366
+ )
367
+
368
+
369
+ @app.command()
370
+ def migrate(config: ConfigOpt = None, yes: Annotated[bool, typer.Option("--yes")] = False) -> None:
371
+ """Upgrade the store schema (takes a consistent pre-migration copy first)."""
372
+ from offgit.server.migrate import MigrationError, migrate_store
373
+
374
+ s = _settings(config)
375
+ if not yes and not (
376
+ sys.stdin.isatty() and typer.confirm("Migrate the store schema?", err=True)
377
+ ):
378
+ _fail("confirmation required: re-run with --yes", 2)
379
+ try:
380
+ res = migrate_store(s)
381
+ except MigrationError as exc:
382
+ _fail(str(exc))
383
+ typer.echo(res)
384
+
385
+
386
+ def main() -> None:
387
+ app(prog_name="offgit-server")
388
+
389
+
390
+ if __name__ == "__main__": # pragma: no cover
391
+ main()
@@ -0,0 +1,75 @@
1
+ """Read-only human-readable export: ``manifest.json`` + ``files/<path>``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from offgit.identity import project_key
11
+ from offgit.paths import Root
12
+ from offgit.server.store import RpcError, Store
13
+
14
+
15
+ class ExportError(Exception):
16
+ pass
17
+
18
+
19
+ def resolve_project(store: Store, project: str) -> tuple[str, str]:
20
+ row = store.conn.execute(
21
+ "SELECT id, canonical_remote FROM projects WHERE id=? OR canonical_remote=?",
22
+ (project, project),
23
+ ).fetchone()
24
+ if row is None:
25
+ raise ExportError(f"no such project: {project}")
26
+ return row[0], row[1]
27
+
28
+
29
+ def export_project(
30
+ store: Store, project: str, destination: Path, revision: int | None = None
31
+ ) -> dict[str, Any]:
32
+ pid, canonical = resolve_project(store, project)
33
+ if project_key(canonical) != pid:
34
+ raise ExportError("stored project id does not match identity")
35
+ destination.mkdir(mode=0o700, parents=True, exist_ok=True)
36
+ if any(destination.iterdir()):
37
+ raise ExportError(f"{destination} is not empty")
38
+ store.conn.execute("BEGIN")
39
+ try:
40
+ head = store.conn.execute("SELECT revision FROM projects WHERE id=?", (pid,)).fetchone()[0]
41
+ rev = revision or head
42
+ if not 1 <= rev <= head:
43
+ raise ExportError(f"revision {rev} does not exist (head {head})")
44
+ entries = store._manifest(pid, rev)
45
+ files_dir = destination / "files"
46
+ files_dir.mkdir(mode=0o700)
47
+ manifest_files = []
48
+ with Root(str(files_dir)) as root:
49
+ for path, e in sorted(entries.items()):
50
+ manifest_files.append(
51
+ {"path": path, "sha256": e.sha256, "size": e.size, "registered": e.registered}
52
+ )
53
+ if not e.registered:
54
+ continue
55
+ try:
56
+ data = store._blob(e.sha256)
57
+ except RpcError as exc:
58
+ raise ExportError(f"{path}: {exc.message}") from exc
59
+ root.atomic_write(path, data, expected_sha256=None, max_bytes=max(len(data), 1))
60
+ finally:
61
+ if store.conn.in_transaction:
62
+ store.conn.execute("COMMIT")
63
+ manifest = {
64
+ "schema_version": 1,
65
+ "canonical_remote": canonical,
66
+ "project_id": pid,
67
+ "revision": rev,
68
+ "files": manifest_files,
69
+ }
70
+ mpath = destination / "manifest.json"
71
+ fd = os.open(mpath, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
72
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
73
+ json.dump(manifest, fh, indent=2, ensure_ascii=False)
74
+ fh.write("\n")
75
+ return manifest
@@ -0,0 +1,59 @@
1
+ """Backup health file (outside the authoritative DB; never included in backups)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from offgit.config import atomic_write_private
12
+
13
+
14
+ def read_health(path: Path) -> dict[str, Any]:
15
+ try:
16
+ data = json.loads(path.read_text(encoding="utf-8"))
17
+ except FileNotFoundError:
18
+ return {}
19
+ except (OSError, ValueError):
20
+ return {"corrupt": True}
21
+ return data if isinstance(data, dict) else {"corrupt": True}
22
+
23
+
24
+ def write_health(path: Path, data: dict[str, Any]) -> None:
25
+ atomic_write_private(path, json.dumps(data, indent=2, sort_keys=True) + "\n")
26
+
27
+
28
+ def _age_seconds(ts: str | None) -> int | None:
29
+ if not ts:
30
+ return None
31
+ try:
32
+ when = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=UTC)
33
+ except ValueError:
34
+ return None
35
+ return max(0, int((datetime.now(UTC) - when).total_seconds()))
36
+
37
+
38
+ def health_summary(path: Path) -> dict[str, Any]:
39
+ """Sanitized summary safe to return over RPC (no errors, paths or IDs)."""
40
+ data = read_health(path)
41
+ if not data:
42
+ return {"configured": False}
43
+ if data.get("corrupt"):
44
+ return {"configured": True, "state": "unknown"}
45
+ age = _age_seconds(data.get("last_success_at"))
46
+ return {
47
+ "configured": True,
48
+ "last_result": data.get("last_result")
49
+ if data.get("last_result") in ("ok", "failed")
50
+ else None,
51
+ "last_success_at": data.get("last_success_at"),
52
+ "last_attempt_at": data.get("last_attempt_at"),
53
+ "last_success_age_seconds": age,
54
+ }
55
+
56
+
57
+ def ensure_private_dir(path: Path) -> None:
58
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
59
+ os.chmod(path, 0o700)
offgit/server/locks.py ADDED
@@ -0,0 +1,48 @@
1
+ """Advisory file locks on the server.
2
+
3
+ Lock order (always acquired in this order, released in reverse) prevents deadlock:
4
+
5
+ 1. ``backup.lock`` exclusive: one backup/prune/restore maintenance job at a time
6
+ 2. ``maintenance.lock`` shared by RPC processes and backup snapshot creation;
7
+ exclusive only for ``restore`` and ``migrate``
8
+
9
+ RPC writes additionally serialize inside SQLite (``BEGIN IMMEDIATE`` + CAS).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import fcntl
16
+ import os
17
+ import time
18
+ from collections.abc import Iterator
19
+ from pathlib import Path
20
+
21
+
22
+ class LockBusy(Exception):
23
+ pass
24
+
25
+
26
+ @contextlib.contextmanager
27
+ def flock(path: Path, *, exclusive: bool, timeout: float) -> Iterator[None]:
28
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
29
+ fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
30
+ try:
31
+ mode = fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH
32
+ deadline = time.monotonic() + timeout
33
+ delay = 0.02
34
+ while True:
35
+ try:
36
+ fcntl.flock(fd, mode | fcntl.LOCK_NB)
37
+ break
38
+ except BlockingIOError as exc:
39
+ if time.monotonic() >= deadline:
40
+ raise LockBusy(path.name) from exc
41
+ time.sleep(delay)
42
+ delay = min(delay * 2, 0.5)
43
+ try:
44
+ yield
45
+ finally:
46
+ fcntl.flock(fd, fcntl.LOCK_UN)
47
+ finally:
48
+ os.close(fd)
@@ -0,0 +1,59 @@
1
+ """Schema migrations with a mandatory consistent pre-migration copy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sqlite3
6
+ from datetime import UTC, datetime
7
+
8
+ from offgit.server.locks import LockBusy, flock
9
+ from offgit.server.migrations import LATEST, MIGRATIONS
10
+ from offgit.server.schema import connect
11
+ from offgit.server.settings import ServerSettings
12
+
13
+
14
+ class MigrationError(Exception):
15
+ pass
16
+
17
+
18
+ def migrate_store(settings: ServerSettings) -> str:
19
+ if not settings.store_path.exists():
20
+ raise MigrationError("store does not exist")
21
+ try:
22
+ with flock(
23
+ settings.locks_dir / "maintenance.lock",
24
+ exclusive=True,
25
+ timeout=settings.lock_timeout_seconds,
26
+ ):
27
+ conn = connect(settings.store_path, busy_timeout_ms=settings.busy_timeout_ms)
28
+ try:
29
+ version = conn.execute("PRAGMA user_version").fetchone()[0]
30
+ if version == LATEST:
31
+ return f"store already at schema {LATEST}"
32
+ if version > LATEST or version < 1:
33
+ raise MigrationError(f"cannot migrate schema {version}")
34
+ settings.pre_restore_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
35
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
36
+ copy = settings.pre_restore_dir / f"pre-migrate-v{version}-{stamp}.sqlite3"
37
+ out = sqlite3.connect(str(copy))
38
+ try:
39
+ conn.backup(out)
40
+ finally:
41
+ out.close()
42
+ conn.execute("BEGIN IMMEDIATE")
43
+ try:
44
+ for v in range(version + 1, LATEST + 1):
45
+ for stmt in [s for s in MIGRATIONS[v].split(";") if s.strip()]:
46
+ conn.execute(stmt)
47
+ conn.execute(
48
+ "UPDATE server_meta SET value=? WHERE key='schema_version'", (str(LATEST),)
49
+ )
50
+ conn.execute(f"PRAGMA user_version = {LATEST}")
51
+ conn.execute("COMMIT")
52
+ except BaseException:
53
+ conn.execute("ROLLBACK")
54
+ raise
55
+ finally:
56
+ conn.close()
57
+ except LockBusy as exc:
58
+ raise MigrationError("store is busy") from exc
59
+ return f"migrated schema {version} -> {LATEST}; pre-migration copy at {copy}"
@@ -0,0 +1,12 @@
1
+ """Ordered schema migrations.
2
+
3
+ ``MIGRATIONS[n]`` upgrades a store from ``user_version == n - 1`` to ``n``.
4
+ Version 1 is the initial schema (applied by ``offgit-server init-store``).
5
+ Each step runs inside one transaction; ``offgit-server migrate`` always takes
6
+ a consistent pre-migration copy first.
7
+ """
8
+
9
+ from offgit.server.migrations.v001_initial import SQL as V001
10
+
11
+ MIGRATIONS: dict[int, str] = {1: V001}
12
+ LATEST = max(MIGRATIONS)