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/__init__.py +4 -0
- offgit/cli.py +498 -0
- offgit/client.py +1636 -0
- offgit/config.py +281 -0
- offgit/errors.py +115 -0
- offgit/gitrepo.py +186 -0
- offgit/hashing.py +22 -0
- offgit/identity.py +243 -0
- offgit/local_state.py +255 -0
- offgit/output.py +160 -0
- offgit/paths.py +367 -0
- offgit/protocol.py +466 -0
- offgit/reconcile.py +169 -0
- offgit/server/__init__.py +1 -0
- offgit/server/backup.py +401 -0
- offgit/server/cli.py +391 -0
- offgit/server/export.py +75 -0
- offgit/server/health.py +59 -0
- offgit/server/locks.py +48 -0
- offgit/server/migrate.py +59 -0
- offgit/server/migrations/__init__.py +12 -0
- offgit/server/migrations/v001_initial.py +57 -0
- offgit/server/restore.py +207 -0
- offgit/server/rpc.py +187 -0
- offgit/server/schema.py +228 -0
- offgit/server/settings.py +140 -0
- offgit/server/store.py +658 -0
- offgit/transport.py +304 -0
- offgit-0.1.0.dist-info/METADATA +171 -0
- offgit-0.1.0.dist-info/RECORD +33 -0
- offgit-0.1.0.dist-info/WHEEL +4 -0
- offgit-0.1.0.dist-info/entry_points.txt +3 -0
- offgit-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""Initial schema (store schema version 1)."""
|
|
2
|
+
|
|
3
|
+
SQL = """
|
|
4
|
+
CREATE TABLE server_meta (
|
|
5
|
+
key TEXT PRIMARY KEY,
|
|
6
|
+
value TEXT NOT NULL
|
|
7
|
+
) STRICT;
|
|
8
|
+
|
|
9
|
+
CREATE TABLE projects (
|
|
10
|
+
id TEXT PRIMARY KEY CHECK (length(id) = 64),
|
|
11
|
+
canonical_remote TEXT NOT NULL UNIQUE,
|
|
12
|
+
revision INTEGER NOT NULL CHECK (revision >= 1),
|
|
13
|
+
created_at TEXT NOT NULL,
|
|
14
|
+
updated_at TEXT NOT NULL
|
|
15
|
+
) STRICT;
|
|
16
|
+
|
|
17
|
+
CREATE TABLE blobs (
|
|
18
|
+
sha256 TEXT PRIMARY KEY CHECK (length(sha256) = 64),
|
|
19
|
+
size INTEGER NOT NULL CHECK (size >= 0),
|
|
20
|
+
data BLOB NOT NULL,
|
|
21
|
+
created_at TEXT NOT NULL,
|
|
22
|
+
CHECK (length(data) = size)
|
|
23
|
+
) STRICT;
|
|
24
|
+
|
|
25
|
+
CREATE TABLE revisions (
|
|
26
|
+
project_id TEXT NOT NULL REFERENCES projects(id),
|
|
27
|
+
revision INTEGER NOT NULL CHECK (revision >= 1),
|
|
28
|
+
timestamp_utc TEXT NOT NULL,
|
|
29
|
+
device TEXT,
|
|
30
|
+
operation TEXT NOT NULL,
|
|
31
|
+
request_id TEXT NOT NULL,
|
|
32
|
+
PRIMARY KEY (project_id, revision)
|
|
33
|
+
) STRICT;
|
|
34
|
+
|
|
35
|
+
CREATE TABLE revision_files (
|
|
36
|
+
project_id TEXT NOT NULL,
|
|
37
|
+
revision INTEGER NOT NULL,
|
|
38
|
+
path TEXT NOT NULL,
|
|
39
|
+
blob_sha256 TEXT NOT NULL REFERENCES blobs(sha256),
|
|
40
|
+
registered INTEGER NOT NULL CHECK (registered IN (0, 1)),
|
|
41
|
+
changed_revision INTEGER NOT NULL,
|
|
42
|
+
PRIMARY KEY (project_id, revision, path),
|
|
43
|
+
FOREIGN KEY (project_id, revision) REFERENCES revisions(project_id, revision),
|
|
44
|
+
CHECK (changed_revision >= 1 AND changed_revision <= revision)
|
|
45
|
+
) STRICT;
|
|
46
|
+
|
|
47
|
+
CREATE TABLE requests (
|
|
48
|
+
request_id TEXT PRIMARY KEY,
|
|
49
|
+
project_id TEXT NOT NULL,
|
|
50
|
+
operation TEXT NOT NULL,
|
|
51
|
+
request_digest TEXT NOT NULL,
|
|
52
|
+
response_json TEXT NOT NULL,
|
|
53
|
+
created_at TEXT NOT NULL
|
|
54
|
+
) STRICT;
|
|
55
|
+
|
|
56
|
+
CREATE INDEX requests_created ON requests(created_at);
|
|
57
|
+
"""
|
offgit/server/restore.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Install a validated snapshot as the live store (never over a live DB in place).
|
|
2
|
+
|
|
3
|
+
Lock order: ``backup.lock`` (exclusive) then ``maintenance.lock`` (exclusive).
|
|
4
|
+
RPC processes hold ``maintenance.lock`` shared, so taking it exclusively waits
|
|
5
|
+
for in-flight requests and blocks new ones until the swap is complete.
|
|
6
|
+
|
|
7
|
+
A restored store always gets a NEW server epoch so clients detect the
|
|
8
|
+
rollback and must ``offgit rebaseline``; the server id is preserved unless
|
|
9
|
+
``new_server_id`` is requested.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import secrets
|
|
18
|
+
import sqlite3
|
|
19
|
+
import uuid
|
|
20
|
+
from datetime import UTC, datetime
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from offgit.server.backup import BACKUP_FORMAT, STAGE_DB, STAGE_MANIFEST
|
|
25
|
+
from offgit.server.locks import LockBusy, flock
|
|
26
|
+
from offgit.server.schema import connect, file_sha256, open_store, utcnow, verify_connection
|
|
27
|
+
from offgit.server.settings import ServerSettings
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RestoreError(Exception):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def locate_stage(directory: Path, max_depth: int = 64) -> Path:
|
|
35
|
+
# restic restores the full absolute source path (e.g. var/lib/offgit/backup-stage, or much
|
|
36
|
+
# deeper for custom data_dir / macOS temp dirs), so the bound must be generous.
|
|
37
|
+
"""Find the directory holding manifest.json + store.sqlite3 (restic keeps full paths)."""
|
|
38
|
+
directory = directory.resolve()
|
|
39
|
+
if (directory / STAGE_MANIFEST).is_file() and (directory / STAGE_DB).is_file():
|
|
40
|
+
return directory
|
|
41
|
+
found: list[Path] = []
|
|
42
|
+
base_depth = len(directory.parts)
|
|
43
|
+
for root, dirs, files in os.walk(directory, followlinks=False):
|
|
44
|
+
if len(Path(root).parts) - base_depth >= max_depth:
|
|
45
|
+
dirs[:] = []
|
|
46
|
+
if STAGE_MANIFEST in files and STAGE_DB in files:
|
|
47
|
+
found.append(Path(root))
|
|
48
|
+
if not found:
|
|
49
|
+
raise RestoreError(
|
|
50
|
+
f"no offgit backup stage (manifest.json + store.sqlite3) under {directory}"
|
|
51
|
+
)
|
|
52
|
+
if len(found) > 1:
|
|
53
|
+
raise RestoreError(
|
|
54
|
+
"several backup stages found; pass the exact directory: " + ", ".join(map(str, found))
|
|
55
|
+
)
|
|
56
|
+
return found[0]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def validate_stage(stage: Path) -> dict[str, Any]:
|
|
60
|
+
try:
|
|
61
|
+
manifest = json.loads((stage / STAGE_MANIFEST).read_text(encoding="utf-8"))
|
|
62
|
+
except (OSError, ValueError) as exc:
|
|
63
|
+
raise RestoreError(f"cannot read {stage / STAGE_MANIFEST}: {exc}") from exc
|
|
64
|
+
if not isinstance(manifest, dict) or manifest.get("format") != BACKUP_FORMAT:
|
|
65
|
+
raise RestoreError("manifest.json is not an offgit backup manifest")
|
|
66
|
+
db = stage / STAGE_DB
|
|
67
|
+
for suffix in ("-wal", "-shm", "-journal"):
|
|
68
|
+
if Path(str(db) + suffix).exists():
|
|
69
|
+
raise RestoreError(f"backup stage contains a stray {suffix} sidecar; refusing")
|
|
70
|
+
digest = file_sha256(db)
|
|
71
|
+
if digest != manifest.get("db_sha256"):
|
|
72
|
+
raise RestoreError("store.sqlite3 does not match the digest recorded in manifest.json")
|
|
73
|
+
conn = connect(db, readonly=True)
|
|
74
|
+
try:
|
|
75
|
+
report = verify_connection(conn)
|
|
76
|
+
finally:
|
|
77
|
+
conn.close()
|
|
78
|
+
if not report.ok:
|
|
79
|
+
raise RestoreError("backup database failed verification: " + "; ".join(report.problems[:5]))
|
|
80
|
+
if report.server_id != manifest.get("server_id") or report.server_epoch != manifest.get(
|
|
81
|
+
"server_epoch"
|
|
82
|
+
):
|
|
83
|
+
raise RestoreError("manifest.json server identity does not match the database")
|
|
84
|
+
return {"manifest": manifest, "verify": report.to_dict()}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def restore_store(
|
|
88
|
+
settings: ServerSettings, source: Path, *, new_server_id: bool = False
|
|
89
|
+
) -> dict[str, Any]:
|
|
90
|
+
stage = locate_stage(source)
|
|
91
|
+
checked = validate_stage(stage)
|
|
92
|
+
data_dir = settings.data_dir
|
|
93
|
+
data_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
94
|
+
live = settings.store_path
|
|
95
|
+
old_umask = os.umask(0o077)
|
|
96
|
+
try:
|
|
97
|
+
with (
|
|
98
|
+
flock(
|
|
99
|
+
settings.locks_dir / "backup.lock",
|
|
100
|
+
exclusive=True,
|
|
101
|
+
timeout=settings.lock_timeout_seconds,
|
|
102
|
+
),
|
|
103
|
+
flock(
|
|
104
|
+
settings.locks_dir / "maintenance.lock",
|
|
105
|
+
exclusive=True,
|
|
106
|
+
timeout=settings.lock_timeout_seconds,
|
|
107
|
+
),
|
|
108
|
+
):
|
|
109
|
+
tmp = data_dir / f"store.sqlite3.restore-{secrets.token_hex(4)}"
|
|
110
|
+
src = connect(stage / STAGE_DB, readonly=True)
|
|
111
|
+
dst = sqlite3.connect(str(tmp), isolation_level=None)
|
|
112
|
+
try:
|
|
113
|
+
src.backup(dst)
|
|
114
|
+
finally:
|
|
115
|
+
src.close()
|
|
116
|
+
new_epoch = str(uuid.uuid4())
|
|
117
|
+
try:
|
|
118
|
+
dst.execute("PRAGMA journal_mode = WAL")
|
|
119
|
+
dst.execute("PRAGMA foreign_keys = ON")
|
|
120
|
+
dst.execute("BEGIN IMMEDIATE")
|
|
121
|
+
dst.execute("UPDATE server_meta SET value=? WHERE key='server_epoch'", (new_epoch,))
|
|
122
|
+
if new_server_id:
|
|
123
|
+
dst.execute(
|
|
124
|
+
"UPDATE server_meta SET value=? WHERE key='server_id'", (str(uuid.uuid4()),)
|
|
125
|
+
)
|
|
126
|
+
for key, value in (
|
|
127
|
+
("restored_at", utcnow()),
|
|
128
|
+
("restored_from_captured_at", str(checked["manifest"].get("captured_at"))),
|
|
129
|
+
("restored_from_epoch", str(checked["manifest"].get("server_epoch"))),
|
|
130
|
+
):
|
|
131
|
+
dst.execute(
|
|
132
|
+
"INSERT INTO server_meta(key, value) VALUES (?, ?) "
|
|
133
|
+
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
|
|
134
|
+
(key, value),
|
|
135
|
+
)
|
|
136
|
+
# stale idempotency records from the old timeline must not be replayed
|
|
137
|
+
dst.execute("DELETE FROM requests")
|
|
138
|
+
dst.execute("COMMIT")
|
|
139
|
+
dst.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
140
|
+
finally:
|
|
141
|
+
dst.close()
|
|
142
|
+
for suffix in ("-wal", "-shm"):
|
|
143
|
+
side = Path(str(tmp) + suffix)
|
|
144
|
+
if side.exists() and side.stat().st_size > 0 and suffix == "-wal":
|
|
145
|
+
raise RestoreError("could not checkpoint the restored database")
|
|
146
|
+
with contextlib.suppress(FileNotFoundError):
|
|
147
|
+
side.unlink()
|
|
148
|
+
os.chmod(tmp, 0o600)
|
|
149
|
+
fd = os.open(tmp, os.O_RDONLY)
|
|
150
|
+
try:
|
|
151
|
+
os.fsync(fd)
|
|
152
|
+
finally:
|
|
153
|
+
os.close(fd)
|
|
154
|
+
|
|
155
|
+
safety_copy = None
|
|
156
|
+
if live.exists():
|
|
157
|
+
settings.pre_restore_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
158
|
+
stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
|
|
159
|
+
safety_copy = (
|
|
160
|
+
settings.pre_restore_dir / f"store-{stamp}-{secrets.token_hex(3)}.sqlite3"
|
|
161
|
+
)
|
|
162
|
+
cur = connect(live)
|
|
163
|
+
try:
|
|
164
|
+
out = sqlite3.connect(str(safety_copy))
|
|
165
|
+
try:
|
|
166
|
+
cur.backup(out)
|
|
167
|
+
out.execute("PRAGMA journal_mode = DELETE")
|
|
168
|
+
finally:
|
|
169
|
+
out.close()
|
|
170
|
+
busy, _log, _ckpt = cur.execute("PRAGMA wal_checkpoint(TRUNCATE)").fetchone()
|
|
171
|
+
if busy:
|
|
172
|
+
raise RestoreError("live store is busy; stop other SQLite users and retry")
|
|
173
|
+
finally:
|
|
174
|
+
cur.close()
|
|
175
|
+
os.chmod(safety_copy, 0o600)
|
|
176
|
+
for suffix in ("-wal", "-shm"):
|
|
177
|
+
with contextlib.suppress(FileNotFoundError):
|
|
178
|
+
Path(str(live) + suffix).unlink()
|
|
179
|
+
os.replace(tmp, live)
|
|
180
|
+
dfd = os.open(data_dir, os.O_RDONLY)
|
|
181
|
+
try:
|
|
182
|
+
os.fsync(dfd)
|
|
183
|
+
finally:
|
|
184
|
+
os.close(dfd)
|
|
185
|
+
conn = open_store(live, busy_timeout_ms=settings.busy_timeout_ms)
|
|
186
|
+
try:
|
|
187
|
+
report = verify_connection(conn)
|
|
188
|
+
finally:
|
|
189
|
+
conn.close()
|
|
190
|
+
if not report.ok:
|
|
191
|
+
raise RestoreError(
|
|
192
|
+
"restored store failed verification; previous store is at " + str(safety_copy)
|
|
193
|
+
)
|
|
194
|
+
except LockBusy as exc:
|
|
195
|
+
raise RestoreError(
|
|
196
|
+
"could not acquire maintenance locks (active backup or requests)"
|
|
197
|
+
) from exc
|
|
198
|
+
finally:
|
|
199
|
+
os.umask(old_umask)
|
|
200
|
+
return {
|
|
201
|
+
"stage": str(stage),
|
|
202
|
+
"server_id": report.server_id,
|
|
203
|
+
"server_epoch": report.server_epoch,
|
|
204
|
+
"previous_store_copy": str(safety_copy) if safety_copy else None,
|
|
205
|
+
"projects": report.projects,
|
|
206
|
+
"revisions": report.revisions,
|
|
207
|
+
}
|
offgit/server/rpc.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""RPC dispatcher: one bounded JSON request on stdin, one JSON response on stdout.
|
|
2
|
+
|
|
3
|
+
Launched by sshd as a forced command (``offgit-server rpc``). It takes no
|
|
4
|
+
arguments from the caller, never accepts paths/commands/credentials, and only
|
|
5
|
+
dispatches the allowlisted operations in :mod:`offgit.protocol`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sqlite3
|
|
12
|
+
import sys
|
|
13
|
+
import traceback
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from typing import IO, Any
|
|
16
|
+
|
|
17
|
+
from offgit import __version__
|
|
18
|
+
from offgit.errors import ProtocolError
|
|
19
|
+
from offgit.protocol import (
|
|
20
|
+
MAX_MESSAGE_BYTES,
|
|
21
|
+
SUPPORTED_VERSIONS,
|
|
22
|
+
canonical_digest,
|
|
23
|
+
dumps,
|
|
24
|
+
error_response,
|
|
25
|
+
loads_strict,
|
|
26
|
+
ok_response,
|
|
27
|
+
validate_request,
|
|
28
|
+
)
|
|
29
|
+
from offgit.server.health import health_summary
|
|
30
|
+
from offgit.server.locks import LockBusy, flock
|
|
31
|
+
from offgit.server.schema import StoreError
|
|
32
|
+
from offgit.server.settings import ServerSettings, SettingsError, load_settings
|
|
33
|
+
from offgit.server.store import RpcError, Store
|
|
34
|
+
|
|
35
|
+
StoreFactory = Callable[[ServerSettings], Store]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _log(msg: str) -> None:
|
|
39
|
+
# Diagnostics only: never file contents, never credentials.
|
|
40
|
+
print(f"offgit-server: {msg}", file=sys.stderr)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def dispatch(store: Store, req: dict[str, Any], digest: str) -> dict[str, Any]:
|
|
44
|
+
op = req["operation"]
|
|
45
|
+
settings = store.settings
|
|
46
|
+
if op == "hello":
|
|
47
|
+
return {
|
|
48
|
+
"protocol_versions": list(SUPPORTED_VERSIONS),
|
|
49
|
+
"server_version": __version__,
|
|
50
|
+
"limits": dict(settings.limits),
|
|
51
|
+
"backup": health_summary(settings.health_path),
|
|
52
|
+
}
|
|
53
|
+
if op == "manifest":
|
|
54
|
+
result = store.manifest(req["project"])
|
|
55
|
+
result["limits"] = dict(settings.limits)
|
|
56
|
+
result["backup"] = health_summary(settings.health_path)
|
|
57
|
+
return result
|
|
58
|
+
if op == "projects":
|
|
59
|
+
return store.projects()
|
|
60
|
+
if op == "fetch":
|
|
61
|
+
return store.fetch(req["project"], req["expected_revision"], req["paths"])
|
|
62
|
+
if op == "history":
|
|
63
|
+
return store.history(req["project"], req["path"], req["limit"])
|
|
64
|
+
if op == "get_file":
|
|
65
|
+
return store.get_file(req["project"], req["revision"], req["path"])
|
|
66
|
+
if op == "init":
|
|
67
|
+
return store.op_init(req, digest)
|
|
68
|
+
if op == "push":
|
|
69
|
+
return store.op_push(req, digest)
|
|
70
|
+
if op == "add":
|
|
71
|
+
return store.op_add(req, digest)
|
|
72
|
+
if op == "remove":
|
|
73
|
+
return store.op_remove(req, digest)
|
|
74
|
+
if op == "restore":
|
|
75
|
+
return store.op_restore(req, digest)
|
|
76
|
+
if op == "settle_request":
|
|
77
|
+
return store.op_settle(req)
|
|
78
|
+
raise RpcError("unknown_operation", f"unknown operation {op!r}") # pragma: no cover
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def handle_request_bytes(
|
|
82
|
+
raw: bytes,
|
|
83
|
+
settings: ServerSettings,
|
|
84
|
+
*,
|
|
85
|
+
store_factory: StoreFactory | None = None,
|
|
86
|
+
) -> bytes:
|
|
87
|
+
"""Process one framed request and return the framed response bytes."""
|
|
88
|
+
request_id: str | None = None
|
|
89
|
+
server_block: dict[str, Any] | None = None
|
|
90
|
+
try:
|
|
91
|
+
doc = loads_strict(raw, max_bytes=MAX_MESSAGE_BYTES)
|
|
92
|
+
if isinstance(doc, dict) and isinstance(doc.get("request_id"), str):
|
|
93
|
+
rid = doc["request_id"]
|
|
94
|
+
request_id = rid if len(rid) <= 64 else None
|
|
95
|
+
req = validate_request(doc, settings.limits)
|
|
96
|
+
digest = canonical_digest(doc)
|
|
97
|
+
with flock(
|
|
98
|
+
settings.locks_dir / "maintenance.lock",
|
|
99
|
+
exclusive=False,
|
|
100
|
+
timeout=settings.lock_timeout_seconds,
|
|
101
|
+
):
|
|
102
|
+
store = (store_factory or Store)(settings)
|
|
103
|
+
try:
|
|
104
|
+
server_block = store.server_block()
|
|
105
|
+
result = dispatch(store, req, digest)
|
|
106
|
+
finally:
|
|
107
|
+
store.close()
|
|
108
|
+
return dumps(ok_response(request_id, server_block, result))
|
|
109
|
+
except RpcError as exc:
|
|
110
|
+
return dumps(error_response(request_id, server_block, exc.code, exc.message, exc.details))
|
|
111
|
+
except ProtocolError as exc:
|
|
112
|
+
return dumps(
|
|
113
|
+
error_response(request_id, server_block, exc.code, exc.message, exc.details or None)
|
|
114
|
+
)
|
|
115
|
+
except StoreError as exc:
|
|
116
|
+
return dumps(error_response(request_id, server_block, exc.code, exc.message))
|
|
117
|
+
except LockBusy:
|
|
118
|
+
return dumps(
|
|
119
|
+
error_response(
|
|
120
|
+
request_id,
|
|
121
|
+
server_block,
|
|
122
|
+
"server_busy",
|
|
123
|
+
"server is in maintenance (restore/migration); retry later",
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
except sqlite3.OperationalError as exc:
|
|
127
|
+
busy = "locked" in str(exc) or "busy" in str(exc)
|
|
128
|
+
if not busy:
|
|
129
|
+
_log(f"database error: {exc}")
|
|
130
|
+
return dumps(
|
|
131
|
+
error_response(
|
|
132
|
+
request_id,
|
|
133
|
+
server_block,
|
|
134
|
+
"server_busy" if busy else "storage_error",
|
|
135
|
+
"database is busy; retry" if busy else "server storage error",
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
except (sqlite3.Error, OSError) as exc:
|
|
139
|
+
_log(f"storage error: {type(exc).__name__}: {exc}")
|
|
140
|
+
return dumps(
|
|
141
|
+
error_response(request_id, server_block, "storage_error", "server storage error")
|
|
142
|
+
)
|
|
143
|
+
except Exception as exc: # never leak tracebacks over the protocol
|
|
144
|
+
_log(f"internal error: {type(exc).__name__}")
|
|
145
|
+
if os.environ.get("OFFGIT_DEBUG"):
|
|
146
|
+
traceback.print_exc(file=sys.stderr)
|
|
147
|
+
return dumps(
|
|
148
|
+
error_response(request_id, server_block, "internal_error", "internal server error")
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def read_bounded(stream: IO[bytes], limit: int) -> bytes:
|
|
153
|
+
chunks: list[bytes] = []
|
|
154
|
+
total = 0
|
|
155
|
+
while True:
|
|
156
|
+
chunk = stream.read(min(1 << 20, limit + 1 - total))
|
|
157
|
+
if not chunk:
|
|
158
|
+
break
|
|
159
|
+
chunks.append(chunk)
|
|
160
|
+
total += len(chunk)
|
|
161
|
+
if total > limit:
|
|
162
|
+
raise ProtocolError("request exceeds size limit", code="message_too_large")
|
|
163
|
+
return b"".join(chunks)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def serve(stdin: IO[bytes] | None = None, stdout: IO[bytes] | None = None) -> int:
|
|
167
|
+
os.umask(0o077)
|
|
168
|
+
stdin = stdin or sys.stdin.buffer
|
|
169
|
+
stdout = stdout or sys.stdout.buffer
|
|
170
|
+
try:
|
|
171
|
+
settings = load_settings()
|
|
172
|
+
except SettingsError as exc:
|
|
173
|
+
_log(f"configuration error: {exc}")
|
|
174
|
+
stdout.write(
|
|
175
|
+
dumps(error_response(None, None, "server_misconfigured", "server misconfigured"))
|
|
176
|
+
)
|
|
177
|
+
stdout.flush()
|
|
178
|
+
return 1
|
|
179
|
+
try:
|
|
180
|
+
raw = read_bounded(stdin, MAX_MESSAGE_BYTES)
|
|
181
|
+
except ProtocolError as exc:
|
|
182
|
+
stdout.write(dumps(error_response(None, None, exc.code, exc.message)))
|
|
183
|
+
stdout.flush()
|
|
184
|
+
return 1
|
|
185
|
+
stdout.write(handle_request_bytes(raw, settings))
|
|
186
|
+
stdout.flush()
|
|
187
|
+
return 0
|
offgit/server/schema.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""SQLite connection setup, store creation, schema checks and full verification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import os
|
|
7
|
+
import sqlite3
|
|
8
|
+
import uuid
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import UTC, datetime
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from offgit.identity import project_key
|
|
14
|
+
from offgit.paths import validate_rel_path
|
|
15
|
+
from offgit.server.migrations import LATEST, MIGRATIONS
|
|
16
|
+
|
|
17
|
+
SCHEMA_VERSION = LATEST
|
|
18
|
+
MIN_SQLITE = (3, 37, 0) # STRICT tables
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class StoreError(Exception):
|
|
22
|
+
def __init__(self, code: str, message: str) -> None:
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.code = code
|
|
25
|
+
self.message = message
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def utcnow() -> str:
|
|
29
|
+
return datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def check_sqlite_version() -> None:
|
|
33
|
+
if sqlite3.sqlite_version_info < MIN_SQLITE:
|
|
34
|
+
raise StoreError(
|
|
35
|
+
"sqlite_too_old",
|
|
36
|
+
f"SQLite {sqlite3.sqlite_version} is too old; offgit needs >= 3.37",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def connect(
|
|
41
|
+
path: Path, *, busy_timeout_ms: int = 5000, readonly: bool = False
|
|
42
|
+
) -> sqlite3.Connection:
|
|
43
|
+
check_sqlite_version()
|
|
44
|
+
if readonly:
|
|
45
|
+
uri = f"file:{path}?mode=ro"
|
|
46
|
+
conn = sqlite3.connect(uri, uri=True, isolation_level=None, timeout=busy_timeout_ms / 1000)
|
|
47
|
+
else:
|
|
48
|
+
conn = sqlite3.connect(str(path), isolation_level=None, timeout=busy_timeout_ms / 1000)
|
|
49
|
+
conn.execute("PRAGMA foreign_keys = ON")
|
|
50
|
+
conn.execute(f"PRAGMA busy_timeout = {int(busy_timeout_ms)}")
|
|
51
|
+
if not readonly:
|
|
52
|
+
conn.execute("PRAGMA synchronous = FULL")
|
|
53
|
+
return conn
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def open_store(path: Path, *, busy_timeout_ms: int = 5000) -> sqlite3.Connection:
|
|
57
|
+
if not path.exists():
|
|
58
|
+
raise StoreError(
|
|
59
|
+
"server_not_initialized",
|
|
60
|
+
"offgit store does not exist; run 'offgit-server init-store' as the offgit user",
|
|
61
|
+
)
|
|
62
|
+
conn = connect(path, busy_timeout_ms=busy_timeout_ms)
|
|
63
|
+
try:
|
|
64
|
+
check_schema(conn)
|
|
65
|
+
mode = conn.execute("PRAGMA journal_mode").fetchone()[0]
|
|
66
|
+
if mode.lower() != "wal":
|
|
67
|
+
raise StoreError("invalid_store", f"store journal_mode is {mode}, expected wal")
|
|
68
|
+
except BaseException:
|
|
69
|
+
conn.close()
|
|
70
|
+
raise
|
|
71
|
+
return conn
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def check_schema(conn: sqlite3.Connection) -> int:
|
|
75
|
+
version = conn.execute("PRAGMA user_version").fetchone()[0]
|
|
76
|
+
if version == 0:
|
|
77
|
+
raise StoreError("invalid_store", "database is not an offgit store (user_version 0)")
|
|
78
|
+
if version > SCHEMA_VERSION:
|
|
79
|
+
raise StoreError(
|
|
80
|
+
"schema_too_new",
|
|
81
|
+
f"store schema {version} is newer than this offgit ({SCHEMA_VERSION}); upgrade offgit",
|
|
82
|
+
)
|
|
83
|
+
if version < SCHEMA_VERSION:
|
|
84
|
+
raise StoreError(
|
|
85
|
+
"migration_required",
|
|
86
|
+
f"store schema {version} needs migration to {SCHEMA_VERSION}; "
|
|
87
|
+
"run 'offgit-server migrate' (it backs up first)",
|
|
88
|
+
)
|
|
89
|
+
meta = dict(conn.execute("SELECT key, value FROM server_meta").fetchall())
|
|
90
|
+
for key in ("server_id", "server_epoch", "schema_version"):
|
|
91
|
+
if key not in meta:
|
|
92
|
+
raise StoreError("invalid_store", f"server_meta is missing {key}")
|
|
93
|
+
if meta["schema_version"] != str(version):
|
|
94
|
+
raise StoreError("invalid_store", "server_meta schema_version disagrees with user_version")
|
|
95
|
+
return int(version)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def init_store(path: Path) -> tuple[str, str]:
|
|
99
|
+
"""Create a new, empty store. Refuses to touch an existing file."""
|
|
100
|
+
check_sqlite_version()
|
|
101
|
+
if path.exists():
|
|
102
|
+
raise StoreError("store_exists", f"{path} already exists; refusing to overwrite")
|
|
103
|
+
old_umask = os.umask(0o077)
|
|
104
|
+
try:
|
|
105
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
106
|
+
conn = connect(path)
|
|
107
|
+
try:
|
|
108
|
+
conn.execute("PRAGMA journal_mode = WAL")
|
|
109
|
+
server_id, epoch = str(uuid.uuid4()), str(uuid.uuid4())
|
|
110
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
111
|
+
for version in sorted(MIGRATIONS):
|
|
112
|
+
for stmt in _split_sql(MIGRATIONS[version]):
|
|
113
|
+
conn.execute(stmt)
|
|
114
|
+
conn.executemany(
|
|
115
|
+
"INSERT INTO server_meta(key, value) VALUES (?, ?)",
|
|
116
|
+
[
|
|
117
|
+
("server_id", server_id),
|
|
118
|
+
("server_epoch", epoch),
|
|
119
|
+
("schema_version", str(SCHEMA_VERSION)),
|
|
120
|
+
("created_at", utcnow()),
|
|
121
|
+
],
|
|
122
|
+
)
|
|
123
|
+
conn.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
|
|
124
|
+
conn.execute("COMMIT")
|
|
125
|
+
finally:
|
|
126
|
+
conn.close()
|
|
127
|
+
os.chmod(path, 0o600)
|
|
128
|
+
finally:
|
|
129
|
+
os.umask(old_umask)
|
|
130
|
+
return server_id, epoch
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _split_sql(script: str) -> list[str]:
|
|
134
|
+
return [s.strip() for s in script.split(";") if s.strip()]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def file_sha256(path: Path) -> str:
|
|
138
|
+
h = hashlib.sha256()
|
|
139
|
+
with open(path, "rb") as fh:
|
|
140
|
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
|
141
|
+
h.update(chunk)
|
|
142
|
+
return h.hexdigest()
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass
|
|
146
|
+
class VerifyReport:
|
|
147
|
+
ok: bool = True
|
|
148
|
+
problems: list[str] = field(default_factory=list)
|
|
149
|
+
projects: int = 0
|
|
150
|
+
revisions: int = 0
|
|
151
|
+
blobs: int = 0
|
|
152
|
+
blob_bytes: int = 0
|
|
153
|
+
schema_version: int = 0
|
|
154
|
+
server_id: str | None = None
|
|
155
|
+
server_epoch: str | None = None
|
|
156
|
+
|
|
157
|
+
def fail(self, msg: str) -> None:
|
|
158
|
+
self.ok = False
|
|
159
|
+
if len(self.problems) < 200:
|
|
160
|
+
self.problems.append(msg)
|
|
161
|
+
|
|
162
|
+
def to_dict(self) -> dict:
|
|
163
|
+
return {
|
|
164
|
+
"ok": self.ok,
|
|
165
|
+
"problems": self.problems,
|
|
166
|
+
"projects": self.projects,
|
|
167
|
+
"revisions": self.revisions,
|
|
168
|
+
"blobs": self.blobs,
|
|
169
|
+
"blob_bytes": self.blob_bytes,
|
|
170
|
+
"schema_version": self.schema_version,
|
|
171
|
+
"server_id": self.server_id,
|
|
172
|
+
"server_epoch": self.server_epoch,
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def verify_connection(conn: sqlite3.Connection) -> VerifyReport:
|
|
177
|
+
"""Full consistency check: SQLite integrity, FKs, schema, blob digests, manifests."""
|
|
178
|
+
rep = VerifyReport()
|
|
179
|
+
integrity = conn.execute("PRAGMA integrity_check").fetchall()
|
|
180
|
+
if integrity != [("ok",)]:
|
|
181
|
+
rep.fail(f"integrity_check: {integrity[:5]}")
|
|
182
|
+
return rep
|
|
183
|
+
fk = conn.execute("PRAGMA foreign_key_check").fetchall()
|
|
184
|
+
if fk:
|
|
185
|
+
rep.fail(f"foreign_key_check: {len(fk)} violations")
|
|
186
|
+
try:
|
|
187
|
+
rep.schema_version = check_schema(conn)
|
|
188
|
+
except StoreError as exc:
|
|
189
|
+
rep.fail(exc.message)
|
|
190
|
+
return rep
|
|
191
|
+
meta = dict(conn.execute("SELECT key, value FROM server_meta").fetchall())
|
|
192
|
+
rep.server_id, rep.server_epoch = meta.get("server_id"), meta.get("server_epoch")
|
|
193
|
+
conn.execute("BEGIN")
|
|
194
|
+
try:
|
|
195
|
+
for sha, size, data in conn.execute("SELECT sha256, size, data FROM blobs"):
|
|
196
|
+
rep.blobs += 1
|
|
197
|
+
rep.blob_bytes += size
|
|
198
|
+
if len(data) != size or hashlib.sha256(data).hexdigest() != sha:
|
|
199
|
+
rep.fail(f"blob {sha[:12]} content does not match its digest/size")
|
|
200
|
+
projects = conn.execute("SELECT id, canonical_remote, revision FROM projects").fetchall()
|
|
201
|
+
rep.projects = len(projects)
|
|
202
|
+
for pid, canonical, head in projects:
|
|
203
|
+
if project_key(canonical) != pid:
|
|
204
|
+
rep.fail(f"project {pid[:12]} id does not match canonical identity")
|
|
205
|
+
revs = [
|
|
206
|
+
r[0]
|
|
207
|
+
for r in conn.execute(
|
|
208
|
+
"SELECT revision FROM revisions WHERE project_id=? ORDER BY revision", (pid,)
|
|
209
|
+
)
|
|
210
|
+
]
|
|
211
|
+
rep.revisions += len(revs)
|
|
212
|
+
if revs != list(range(1, head + 1)):
|
|
213
|
+
rep.fail(f"project {canonical}: revisions are not contiguous 1..{head}")
|
|
214
|
+
rows = conn.execute(
|
|
215
|
+
"SELECT revision, path, blob_sha256, registered, changed_revision "
|
|
216
|
+
"FROM revision_files WHERE project_id=?",
|
|
217
|
+
(pid,),
|
|
218
|
+
).fetchall()
|
|
219
|
+
for rev, path, _sha, _reg, changed in rows:
|
|
220
|
+
try:
|
|
221
|
+
validate_rel_path(path)
|
|
222
|
+
except Exception:
|
|
223
|
+
rep.fail(f"project {canonical} r{rev}: invalid path stored")
|
|
224
|
+
if changed > rev:
|
|
225
|
+
rep.fail(f"project {canonical} r{rev}: {path} changed_revision in future")
|
|
226
|
+
finally:
|
|
227
|
+
conn.execute("COMMIT")
|
|
228
|
+
return rep
|