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
offgit/server/store.py
ADDED
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
"""Authoritative transactional store.
|
|
2
|
+
|
|
3
|
+
Every mutation: validate request -> ``BEGIN IMMEDIATE`` -> idempotency lookup ->
|
|
4
|
+
epoch + project + expected-revision (CAS) + per-path checks -> insert missing
|
|
5
|
+
blobs -> new immutable revision + full manifest -> move head -> record request
|
|
6
|
+
-> ``COMMIT``. Any exception rolls the whole thing back.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import sqlite3
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from offgit import __version__
|
|
19
|
+
from offgit.paths import check_collisions
|
|
20
|
+
from offgit.server.schema import StoreError, open_store, utcnow
|
|
21
|
+
from offgit.server.settings import ServerSettings
|
|
22
|
+
|
|
23
|
+
REQUEST_RETENTION = 20_000 # most recent idempotency records kept (see docs/protocol.md)
|
|
24
|
+
ABANDONED = "abandoned"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RpcError(Exception):
|
|
28
|
+
def __init__(self, code: str, message: str, details: dict[str, Any] | None = None) -> None:
|
|
29
|
+
super().__init__(message)
|
|
30
|
+
self.code = code
|
|
31
|
+
self.message = message
|
|
32
|
+
self.details = details or {}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Entry:
|
|
37
|
+
path: str
|
|
38
|
+
sha256: str
|
|
39
|
+
size: int
|
|
40
|
+
registered: bool
|
|
41
|
+
changed_revision: int
|
|
42
|
+
changed_at: str | None = None
|
|
43
|
+
|
|
44
|
+
def to_dict(self) -> dict[str, Any]:
|
|
45
|
+
return {
|
|
46
|
+
"path": self.path,
|
|
47
|
+
"sha256": self.sha256,
|
|
48
|
+
"size": self.size,
|
|
49
|
+
"registered": self.registered,
|
|
50
|
+
"changed_revision": self.changed_revision,
|
|
51
|
+
"changed_at": self.changed_at,
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
FaultHook = Callable[[str], None]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Store:
|
|
59
|
+
def __init__(self, settings: ServerSettings, conn: sqlite3.Connection | None = None) -> None:
|
|
60
|
+
self.settings = settings
|
|
61
|
+
self.conn = conn or open_store(
|
|
62
|
+
settings.store_path, busy_timeout_ms=settings.busy_timeout_ms
|
|
63
|
+
)
|
|
64
|
+
self.fault_hook: FaultHook | None = None
|
|
65
|
+
meta = dict(self.conn.execute("SELECT key, value FROM server_meta").fetchall())
|
|
66
|
+
self.server_id = meta["server_id"]
|
|
67
|
+
self.server_epoch = meta["server_epoch"]
|
|
68
|
+
|
|
69
|
+
def close(self) -> None:
|
|
70
|
+
self.conn.close()
|
|
71
|
+
|
|
72
|
+
def server_block(self) -> dict[str, str]:
|
|
73
|
+
return {"id": self.server_id, "epoch": self.server_epoch, "version": __version__}
|
|
74
|
+
|
|
75
|
+
def _fault(self, phase: str) -> None:
|
|
76
|
+
if self.fault_hook is not None:
|
|
77
|
+
self.fault_hook(phase)
|
|
78
|
+
|
|
79
|
+
# ------------------------------------------------------------------ reads
|
|
80
|
+
|
|
81
|
+
def _begin_read(self) -> None:
|
|
82
|
+
self.conn.execute("BEGIN")
|
|
83
|
+
# force the read snapshot to start now
|
|
84
|
+
self.conn.execute("SELECT 1 FROM server_meta LIMIT 1").fetchone()
|
|
85
|
+
|
|
86
|
+
def _end(self) -> None:
|
|
87
|
+
if self.conn.in_transaction:
|
|
88
|
+
self.conn.execute("COMMIT")
|
|
89
|
+
|
|
90
|
+
def _project(self, pid: str) -> tuple[str, int, str, str] | None:
|
|
91
|
+
row = self.conn.execute(
|
|
92
|
+
"SELECT canonical_remote, revision, created_at, updated_at FROM projects WHERE id=?",
|
|
93
|
+
(pid,),
|
|
94
|
+
).fetchone()
|
|
95
|
+
return row
|
|
96
|
+
|
|
97
|
+
def _require_project(self, project: dict[str, str]) -> int:
|
|
98
|
+
row = self._project(project["id"])
|
|
99
|
+
if row is None:
|
|
100
|
+
raise RpcError(
|
|
101
|
+
"project_not_found",
|
|
102
|
+
"project is not registered on this server",
|
|
103
|
+
{"canonical_remote": project["canonical_remote"]},
|
|
104
|
+
)
|
|
105
|
+
if row[0] != project["canonical_remote"]:
|
|
106
|
+
raise RpcError("invalid_project", "project id collides with a different identity")
|
|
107
|
+
return int(row[1])
|
|
108
|
+
|
|
109
|
+
def _manifest(self, pid: str, revision: int) -> dict[str, Entry]:
|
|
110
|
+
rows = self.conn.execute(
|
|
111
|
+
"SELECT rf.path, rf.blob_sha256, b.size, rf.registered, rf.changed_revision, "
|
|
112
|
+
"r.timestamp_utc FROM revision_files rf "
|
|
113
|
+
"JOIN blobs b ON b.sha256 = rf.blob_sha256 "
|
|
114
|
+
"JOIN revisions r ON r.project_id = rf.project_id AND r.revision = rf.changed_revision "
|
|
115
|
+
"WHERE rf.project_id=? AND rf.revision=? ORDER BY rf.path",
|
|
116
|
+
(pid, revision),
|
|
117
|
+
).fetchall()
|
|
118
|
+
return {p: Entry(p, sha, size, bool(reg), chg, ts) for p, sha, size, reg, chg, ts in rows}
|
|
119
|
+
|
|
120
|
+
def _blob(self, sha: str) -> bytes:
|
|
121
|
+
row = self.conn.execute("SELECT size, data FROM blobs WHERE sha256=?", (sha,)).fetchone()
|
|
122
|
+
if row is None:
|
|
123
|
+
raise RpcError("integrity_error", "referenced blob is missing")
|
|
124
|
+
size, data = row
|
|
125
|
+
if len(data) != size or hashlib.sha256(data).hexdigest() != sha:
|
|
126
|
+
raise RpcError("integrity_error", "stored blob failed verification")
|
|
127
|
+
return bytes(data)
|
|
128
|
+
|
|
129
|
+
def manifest(self, project: dict[str, str]) -> dict[str, Any]:
|
|
130
|
+
self._begin_read()
|
|
131
|
+
try:
|
|
132
|
+
row = self._project(project["id"])
|
|
133
|
+
if row is None:
|
|
134
|
+
return {"exists": False, "revision": 0, "manifest": []}
|
|
135
|
+
if row[0] != project["canonical_remote"]:
|
|
136
|
+
raise RpcError("invalid_project", "project id collides with a different identity")
|
|
137
|
+
head = int(row[1])
|
|
138
|
+
entries = self._manifest(project["id"], head)
|
|
139
|
+
return {
|
|
140
|
+
"exists": True,
|
|
141
|
+
"revision": head,
|
|
142
|
+
"manifest": [e.to_dict() for e in entries.values()],
|
|
143
|
+
}
|
|
144
|
+
finally:
|
|
145
|
+
self._end()
|
|
146
|
+
|
|
147
|
+
def fetch(
|
|
148
|
+
self, project: dict[str, str], expected_revision: int | None, paths: list[str] | None
|
|
149
|
+
) -> dict[str, Any]:
|
|
150
|
+
from offgit.protocol import encode_b64
|
|
151
|
+
|
|
152
|
+
self._begin_read()
|
|
153
|
+
try:
|
|
154
|
+
head = self._require_project(project)
|
|
155
|
+
if expected_revision is not None and expected_revision != head:
|
|
156
|
+
raise RpcError(
|
|
157
|
+
"revision_changed",
|
|
158
|
+
"project revision changed since it was inspected",
|
|
159
|
+
{"expected_revision": expected_revision, "current_revision": head},
|
|
160
|
+
)
|
|
161
|
+
entries = self._manifest(project["id"], head)
|
|
162
|
+
if paths is None:
|
|
163
|
+
wanted = [e for e in entries.values() if e.registered]
|
|
164
|
+
else:
|
|
165
|
+
wanted = []
|
|
166
|
+
for p in paths:
|
|
167
|
+
e = entries.get(p)
|
|
168
|
+
if e is None or not e.registered:
|
|
169
|
+
raise RpcError("not_registered", f"{p} is not registered", {"path": p})
|
|
170
|
+
wanted.append(e)
|
|
171
|
+
contents = [
|
|
172
|
+
{
|
|
173
|
+
"path": e.path,
|
|
174
|
+
"sha256": e.sha256,
|
|
175
|
+
"size": e.size,
|
|
176
|
+
"data_b64": encode_b64(self._blob(e.sha256)),
|
|
177
|
+
}
|
|
178
|
+
for e in wanted
|
|
179
|
+
]
|
|
180
|
+
return {
|
|
181
|
+
"revision": head,
|
|
182
|
+
"manifest": [e.to_dict() for e in entries.values()],
|
|
183
|
+
"contents": contents,
|
|
184
|
+
}
|
|
185
|
+
finally:
|
|
186
|
+
self._end()
|
|
187
|
+
|
|
188
|
+
def get_file(self, project: dict[str, str], revision: int, path: str) -> dict[str, Any]:
|
|
189
|
+
from offgit.protocol import encode_b64
|
|
190
|
+
|
|
191
|
+
self._begin_read()
|
|
192
|
+
try:
|
|
193
|
+
head = self._require_project(project)
|
|
194
|
+
if revision > head:
|
|
195
|
+
raise RpcError("revision_not_found", f"revision {revision} does not exist")
|
|
196
|
+
entry = self._manifest(project["id"], revision).get(path)
|
|
197
|
+
if entry is None:
|
|
198
|
+
raise RpcError("not_found", f"{path} does not exist at revision {revision}")
|
|
199
|
+
return {
|
|
200
|
+
"revision": revision,
|
|
201
|
+
"head_revision": head,
|
|
202
|
+
"entry": entry.to_dict(),
|
|
203
|
+
"data_b64": encode_b64(self._blob(entry.sha256)),
|
|
204
|
+
}
|
|
205
|
+
finally:
|
|
206
|
+
self._end()
|
|
207
|
+
|
|
208
|
+
def history(self, project: dict[str, str], path: str | None, limit: int) -> dict[str, Any]:
|
|
209
|
+
self._begin_read()
|
|
210
|
+
try:
|
|
211
|
+
head = self._require_project(project)
|
|
212
|
+
pid = project["id"]
|
|
213
|
+
params: list[Any] = [pid]
|
|
214
|
+
sql = (
|
|
215
|
+
"SELECT r.revision, r.timestamp_utc, r.device, r.operation FROM revisions r "
|
|
216
|
+
"WHERE r.project_id=? "
|
|
217
|
+
)
|
|
218
|
+
if path is not None:
|
|
219
|
+
sql += (
|
|
220
|
+
"AND EXISTS (SELECT 1 FROM revision_files rf WHERE rf.project_id=r.project_id "
|
|
221
|
+
"AND rf.revision=r.revision AND rf.path=? AND rf.changed_revision=r.revision) "
|
|
222
|
+
)
|
|
223
|
+
params.append(path)
|
|
224
|
+
sql += "ORDER BY r.revision DESC LIMIT ?"
|
|
225
|
+
params.append(limit)
|
|
226
|
+
out = []
|
|
227
|
+
for rev, ts, device, op in self.conn.execute(sql, params).fetchall():
|
|
228
|
+
changes = self.conn.execute(
|
|
229
|
+
"SELECT rf.path, rf.blob_sha256, b.size, rf.registered FROM revision_files rf "
|
|
230
|
+
"JOIN blobs b ON b.sha256=rf.blob_sha256 "
|
|
231
|
+
"WHERE rf.project_id=? AND rf.revision=? AND rf.changed_revision=? "
|
|
232
|
+
"ORDER BY rf.path",
|
|
233
|
+
(pid, rev, rev),
|
|
234
|
+
).fetchall()
|
|
235
|
+
out.append(
|
|
236
|
+
{
|
|
237
|
+
"revision": rev,
|
|
238
|
+
"timestamp_utc": ts,
|
|
239
|
+
"device": device,
|
|
240
|
+
"operation": op,
|
|
241
|
+
"changes": [
|
|
242
|
+
{"path": p, "sha256": s, "size": z, "registered": bool(r)}
|
|
243
|
+
for p, s, z, r in changes
|
|
244
|
+
if path is None or p == path
|
|
245
|
+
],
|
|
246
|
+
}
|
|
247
|
+
)
|
|
248
|
+
return {"revision": head, "revisions": out}
|
|
249
|
+
finally:
|
|
250
|
+
self._end()
|
|
251
|
+
|
|
252
|
+
def projects(self) -> dict[str, Any]:
|
|
253
|
+
self._begin_read()
|
|
254
|
+
try:
|
|
255
|
+
rows = self.conn.execute(
|
|
256
|
+
"SELECT p.id, p.canonical_remote, p.revision, p.updated_at, "
|
|
257
|
+
"COUNT(rf.path), COALESCE(SUM(b.size), 0) FROM projects p "
|
|
258
|
+
"LEFT JOIN revision_files rf ON rf.project_id=p.id AND rf.revision=p.revision "
|
|
259
|
+
"AND rf.registered=1 LEFT JOIN blobs b ON b.sha256=rf.blob_sha256 "
|
|
260
|
+
"GROUP BY p.id ORDER BY p.canonical_remote"
|
|
261
|
+
).fetchall()
|
|
262
|
+
return {
|
|
263
|
+
"projects": [
|
|
264
|
+
{
|
|
265
|
+
"id": pid,
|
|
266
|
+
"canonical_remote": canon,
|
|
267
|
+
"revision": rev,
|
|
268
|
+
"updated_at": upd,
|
|
269
|
+
"files": n,
|
|
270
|
+
"bytes": size,
|
|
271
|
+
}
|
|
272
|
+
for pid, canon, rev, upd, n, size in rows
|
|
273
|
+
]
|
|
274
|
+
}
|
|
275
|
+
finally:
|
|
276
|
+
self._end()
|
|
277
|
+
|
|
278
|
+
def usage(self) -> dict[str, Any]:
|
|
279
|
+
row = self.conn.execute("SELECT COUNT(*), COALESCE(SUM(size), 0) FROM blobs").fetchone()
|
|
280
|
+
revs = self.conn.execute("SELECT COUNT(*) FROM revisions").fetchone()[0]
|
|
281
|
+
projects = self.conn.execute("SELECT COUNT(*) FROM projects").fetchone()[0]
|
|
282
|
+
return {"blobs": row[0], "blob_bytes": row[1], "revisions": revs, "projects": projects}
|
|
283
|
+
|
|
284
|
+
# -------------------------------------------------------------- mutations
|
|
285
|
+
|
|
286
|
+
def mutate(
|
|
287
|
+
self,
|
|
288
|
+
req: dict[str, Any],
|
|
289
|
+
digest: str,
|
|
290
|
+
apply: Callable[[], dict[str, Any]],
|
|
291
|
+
) -> dict[str, Any]:
|
|
292
|
+
"""Run ``apply`` inside one IMMEDIATE transaction with idempotency bookkeeping."""
|
|
293
|
+
conn = self.conn
|
|
294
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
295
|
+
try:
|
|
296
|
+
self._fault("after_begin")
|
|
297
|
+
row = conn.execute(
|
|
298
|
+
"SELECT request_digest, response_json, project_id FROM requests WHERE request_id=?",
|
|
299
|
+
(req["request_id"],),
|
|
300
|
+
).fetchone()
|
|
301
|
+
if row is not None:
|
|
302
|
+
stored_digest, response_json, stored_pid = row
|
|
303
|
+
if stored_digest != digest or stored_pid != req["project"]["id"]:
|
|
304
|
+
raise RpcError(
|
|
305
|
+
"request_id_reused",
|
|
306
|
+
"request_id was already used for a different request",
|
|
307
|
+
)
|
|
308
|
+
result = json.loads(response_json)
|
|
309
|
+
result["replayed"] = True
|
|
310
|
+
conn.execute("COMMIT")
|
|
311
|
+
return result
|
|
312
|
+
if req["expected_server_epoch"] != self.server_epoch:
|
|
313
|
+
raise RpcError(
|
|
314
|
+
"epoch_mismatch",
|
|
315
|
+
"server epoch changed (store was restored or reset); client must rebaseline",
|
|
316
|
+
{"server_epoch": self.server_epoch},
|
|
317
|
+
)
|
|
318
|
+
result = apply()
|
|
319
|
+
self._fault("before_request_record")
|
|
320
|
+
conn.execute(
|
|
321
|
+
"INSERT INTO requests(request_id, project_id, operation, request_digest, "
|
|
322
|
+
"response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
|
323
|
+
(
|
|
324
|
+
req["request_id"],
|
|
325
|
+
req["project"]["id"],
|
|
326
|
+
req["operation"],
|
|
327
|
+
digest,
|
|
328
|
+
json.dumps(result, separators=(",", ":")),
|
|
329
|
+
utcnow(),
|
|
330
|
+
),
|
|
331
|
+
)
|
|
332
|
+
conn.execute(
|
|
333
|
+
"DELETE FROM requests WHERE request_id IN (SELECT request_id FROM requests "
|
|
334
|
+
"ORDER BY created_at DESC LIMIT -1 OFFSET ?)",
|
|
335
|
+
(REQUEST_RETENTION,),
|
|
336
|
+
)
|
|
337
|
+
self._fault("before_commit")
|
|
338
|
+
conn.execute("COMMIT")
|
|
339
|
+
result["replayed"] = False
|
|
340
|
+
return result
|
|
341
|
+
except BaseException:
|
|
342
|
+
if conn.in_transaction:
|
|
343
|
+
conn.execute("ROLLBACK")
|
|
344
|
+
raise
|
|
345
|
+
|
|
346
|
+
def _cas(self, project: dict[str, str], expected_revision: int) -> int:
|
|
347
|
+
head = self._require_project(project)
|
|
348
|
+
if head != expected_revision:
|
|
349
|
+
raise RpcError(
|
|
350
|
+
"revision_conflict",
|
|
351
|
+
"project changed on the server since it was inspected",
|
|
352
|
+
{"expected_revision": expected_revision, "current_revision": head},
|
|
353
|
+
)
|
|
354
|
+
return head
|
|
355
|
+
|
|
356
|
+
def _commit_revision(
|
|
357
|
+
self,
|
|
358
|
+
pid: str,
|
|
359
|
+
base: dict[str, Entry],
|
|
360
|
+
head: int,
|
|
361
|
+
updates: dict[str, tuple[str, bool]],
|
|
362
|
+
blobs: dict[str, bytes],
|
|
363
|
+
req: dict[str, Any],
|
|
364
|
+
) -> dict[str, Any]:
|
|
365
|
+
"""Write a new revision whose manifest is ``base`` with ``updates`` applied.
|
|
366
|
+
|
|
367
|
+
``updates`` maps path -> (sha256, registered). Returns a result dict; if no
|
|
368
|
+
effective change exists, no revision is created.
|
|
369
|
+
"""
|
|
370
|
+
new_rev = head + 1
|
|
371
|
+
changed: list[str] = []
|
|
372
|
+
manifest: dict[str, tuple[str, bool, int]] = {
|
|
373
|
+
p: (e.sha256, e.registered, e.changed_revision) for p, e in base.items()
|
|
374
|
+
}
|
|
375
|
+
for path, (sha, registered) in sorted(updates.items()):
|
|
376
|
+
cur = manifest.get(path)
|
|
377
|
+
if cur is not None and cur[0] == sha and cur[1] == registered:
|
|
378
|
+
continue
|
|
379
|
+
manifest[path] = (sha, registered, new_rev)
|
|
380
|
+
changed.append(path)
|
|
381
|
+
if not changed:
|
|
382
|
+
return {"revision": head, "previous_revision": head, "changed": []}
|
|
383
|
+
|
|
384
|
+
registered_paths = [p for p, v in manifest.items() if v[1]]
|
|
385
|
+
limits = self.settings.limits
|
|
386
|
+
try:
|
|
387
|
+
check_collisions(registered_paths)
|
|
388
|
+
except Exception as exc:
|
|
389
|
+
raise RpcError("path_collision", str(exc)) from exc
|
|
390
|
+
if len(registered_paths) > limits["max_paths"]:
|
|
391
|
+
raise RpcError(
|
|
392
|
+
"limit_exceeded",
|
|
393
|
+
f"project would have {len(registered_paths)} paths (limit {limits['max_paths']})",
|
|
394
|
+
)
|
|
395
|
+
sizes: dict[str, int] = {}
|
|
396
|
+
for sha, data in blobs.items():
|
|
397
|
+
sizes[sha] = len(data)
|
|
398
|
+
for _p, (sha, reg, _c) in manifest.items():
|
|
399
|
+
if reg and sha not in sizes:
|
|
400
|
+
row = self.conn.execute("SELECT size FROM blobs WHERE sha256=?", (sha,)).fetchone()
|
|
401
|
+
if row is None:
|
|
402
|
+
raise RpcError("integrity_error", "manifest references a missing blob")
|
|
403
|
+
sizes[sha] = int(row[0])
|
|
404
|
+
total = sum(sizes[v[0]] for v in manifest.values() if v[1])
|
|
405
|
+
if total > limits["max_project_bytes"]:
|
|
406
|
+
raise RpcError(
|
|
407
|
+
"limit_exceeded",
|
|
408
|
+
f"project would hold {total} bytes (limit {limits['max_project_bytes']})",
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
now = utcnow()
|
|
412
|
+
for sha, data in blobs.items():
|
|
413
|
+
self.conn.execute(
|
|
414
|
+
"INSERT OR IGNORE INTO blobs(sha256, size, data, created_at) VALUES (?, ?, ?, ?)",
|
|
415
|
+
(sha, len(data), sqlite3.Binary(data), now),
|
|
416
|
+
)
|
|
417
|
+
self._fault("after_blobs")
|
|
418
|
+
self.conn.execute(
|
|
419
|
+
"INSERT INTO revisions(project_id, revision, timestamp_utc, device, operation, "
|
|
420
|
+
"request_id) VALUES (?, ?, ?, ?, ?, ?)",
|
|
421
|
+
(pid, new_rev, now, req.get("device"), req["operation"], req["request_id"]),
|
|
422
|
+
)
|
|
423
|
+
self._fault("after_revision")
|
|
424
|
+
self.conn.executemany(
|
|
425
|
+
"INSERT INTO revision_files(project_id, revision, path, blob_sha256, registered, "
|
|
426
|
+
"changed_revision) VALUES (?, ?, ?, ?, ?, ?)",
|
|
427
|
+
[(pid, new_rev, p, v[0], int(v[1]), v[2]) for p, v in sorted(manifest.items())],
|
|
428
|
+
)
|
|
429
|
+
self._fault("after_manifest")
|
|
430
|
+
moved = self.conn.execute(
|
|
431
|
+
"UPDATE projects SET revision=?, updated_at=? WHERE id=? AND revision=?",
|
|
432
|
+
(new_rev, now, pid, head),
|
|
433
|
+
)
|
|
434
|
+
if moved.rowcount != 1:
|
|
435
|
+
raise RpcError("revision_conflict", "project head moved during commit")
|
|
436
|
+
self._fault("after_head")
|
|
437
|
+
entries = self._manifest(pid, new_rev)
|
|
438
|
+
return {
|
|
439
|
+
"revision": new_rev,
|
|
440
|
+
"previous_revision": head,
|
|
441
|
+
"changed": changed,
|
|
442
|
+
"manifest": [e.to_dict() for e in entries.values()],
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
def _with_manifest(self, pid: str, result: dict[str, Any]) -> dict[str, Any]:
|
|
446
|
+
if "manifest" not in result:
|
|
447
|
+
result["manifest"] = [
|
|
448
|
+
e.to_dict() for e in self._manifest(pid, result["revision"]).values()
|
|
449
|
+
]
|
|
450
|
+
return result
|
|
451
|
+
|
|
452
|
+
def op_init(self, req: dict[str, Any], digest: str) -> dict[str, Any]:
|
|
453
|
+
project = req["project"]
|
|
454
|
+
|
|
455
|
+
def apply() -> dict[str, Any]:
|
|
456
|
+
if self._project(project["id"]) is not None:
|
|
457
|
+
raise RpcError(
|
|
458
|
+
"project_exists",
|
|
459
|
+
"project is already registered on this server",
|
|
460
|
+
{"canonical_remote": project["canonical_remote"]},
|
|
461
|
+
)
|
|
462
|
+
if (
|
|
463
|
+
self.conn.execute(
|
|
464
|
+
"SELECT 1 FROM projects WHERE canonical_remote=?",
|
|
465
|
+
(project["canonical_remote"],),
|
|
466
|
+
).fetchone()
|
|
467
|
+
is not None
|
|
468
|
+
):
|
|
469
|
+
raise RpcError("invalid_project", "canonical identity already used")
|
|
470
|
+
now = utcnow()
|
|
471
|
+
# The project row and its first revision are written in one transaction.
|
|
472
|
+
self.conn.execute(
|
|
473
|
+
"INSERT INTO projects(id, canonical_remote, revision, created_at, updated_at) "
|
|
474
|
+
"VALUES (?, ?, 1, ?, ?)",
|
|
475
|
+
(project["id"], project["canonical_remote"], now, now),
|
|
476
|
+
)
|
|
477
|
+
return self._init_revision(project["id"], req)
|
|
478
|
+
|
|
479
|
+
return self.mutate(req, digest, apply)
|
|
480
|
+
|
|
481
|
+
def _init_revision(self, pid: str, req: dict[str, Any]) -> dict[str, Any]:
|
|
482
|
+
files = req["files"]
|
|
483
|
+
updates = {f["path"]: (f["sha256"], True) for f in files}
|
|
484
|
+
blobs = {f["sha256"]: f["data"] for f in files}
|
|
485
|
+
try:
|
|
486
|
+
check_collisions(list(updates))
|
|
487
|
+
except Exception as exc:
|
|
488
|
+
raise RpcError("path_collision", str(exc)) from exc
|
|
489
|
+
limits = self.settings.limits
|
|
490
|
+
if len(updates) > limits["max_paths"]:
|
|
491
|
+
raise RpcError("limit_exceeded", "too many paths")
|
|
492
|
+
total = sum(f["size"] for f in files)
|
|
493
|
+
if total > limits["max_project_bytes"]:
|
|
494
|
+
raise RpcError("limit_exceeded", "project content exceeds limit")
|
|
495
|
+
now = utcnow()
|
|
496
|
+
for sha, data in blobs.items():
|
|
497
|
+
self.conn.execute(
|
|
498
|
+
"INSERT OR IGNORE INTO blobs(sha256, size, data, created_at) VALUES (?, ?, ?, ?)",
|
|
499
|
+
(sha, len(data), sqlite3.Binary(data), now),
|
|
500
|
+
)
|
|
501
|
+
self._fault("after_blobs")
|
|
502
|
+
self.conn.execute(
|
|
503
|
+
"INSERT INTO revisions(project_id, revision, timestamp_utc, device, operation, "
|
|
504
|
+
"request_id) VALUES (?, 1, ?, ?, 'init', ?)",
|
|
505
|
+
(pid, now, req.get("device"), req["request_id"]),
|
|
506
|
+
)
|
|
507
|
+
self._fault("after_revision")
|
|
508
|
+
self.conn.executemany(
|
|
509
|
+
"INSERT INTO revision_files(project_id, revision, path, blob_sha256, registered, "
|
|
510
|
+
"changed_revision) VALUES (?, 1, ?, ?, 1, 1)",
|
|
511
|
+
[(pid, p, v[0]) for p, v in sorted(updates.items())],
|
|
512
|
+
)
|
|
513
|
+
self._fault("after_manifest")
|
|
514
|
+
self._fault("after_head")
|
|
515
|
+
entries = self._manifest(pid, 1)
|
|
516
|
+
return {
|
|
517
|
+
"revision": 1,
|
|
518
|
+
"previous_revision": 0,
|
|
519
|
+
"changed": sorted(updates),
|
|
520
|
+
"manifest": [e.to_dict() for e in entries.values()],
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
def op_push(self, req: dict[str, Any], digest: str) -> dict[str, Any]:
|
|
524
|
+
project = req["project"]
|
|
525
|
+
|
|
526
|
+
def apply() -> dict[str, Any]:
|
|
527
|
+
head = self._cas(project, req["expected_revision"])
|
|
528
|
+
base = self._manifest(project["id"], head)
|
|
529
|
+
updates: dict[str, tuple[str, bool]] = {}
|
|
530
|
+
blobs: dict[str, bytes] = {}
|
|
531
|
+
for ch in req["changes"]:
|
|
532
|
+
cur = base.get(ch["path"])
|
|
533
|
+
if cur is None or not cur.registered:
|
|
534
|
+
raise RpcError(
|
|
535
|
+
"not_registered", f"{ch['path']} is not registered", {"path": ch["path"]}
|
|
536
|
+
)
|
|
537
|
+
if ch["expected_sha256"] != cur.sha256:
|
|
538
|
+
raise RpcError(
|
|
539
|
+
"path_conflict",
|
|
540
|
+
f"{ch['path']} changed on the server",
|
|
541
|
+
{"path": ch["path"], "current_sha256": cur.sha256},
|
|
542
|
+
)
|
|
543
|
+
updates[ch["path"]] = (ch["sha256"], True)
|
|
544
|
+
blobs[ch["sha256"]] = ch["data"]
|
|
545
|
+
return self._with_manifest(
|
|
546
|
+
project["id"], self._commit_revision(project["id"], base, head, updates, blobs, req)
|
|
547
|
+
)
|
|
548
|
+
|
|
549
|
+
return self.mutate(req, digest, apply)
|
|
550
|
+
|
|
551
|
+
def op_add(self, req: dict[str, Any], digest: str) -> dict[str, Any]:
|
|
552
|
+
project = req["project"]
|
|
553
|
+
|
|
554
|
+
def apply() -> dict[str, Any]:
|
|
555
|
+
head = self._cas(project, req["expected_revision"])
|
|
556
|
+
base = self._manifest(project["id"], head)
|
|
557
|
+
updates: dict[str, tuple[str, bool]] = {}
|
|
558
|
+
blobs: dict[str, bytes] = {}
|
|
559
|
+
for f in req["files"]:
|
|
560
|
+
cur = base.get(f["path"])
|
|
561
|
+
if cur is not None and cur.registered:
|
|
562
|
+
raise RpcError(
|
|
563
|
+
"already_registered",
|
|
564
|
+
f"{f['path']} is already registered",
|
|
565
|
+
{"path": f["path"]},
|
|
566
|
+
)
|
|
567
|
+
updates[f["path"]] = (f["sha256"], True)
|
|
568
|
+
blobs[f["sha256"]] = f["data"]
|
|
569
|
+
result = self._commit_revision(project["id"], base, head, updates, blobs, req)
|
|
570
|
+
return self._with_manifest(project["id"], result)
|
|
571
|
+
|
|
572
|
+
return self.mutate(req, digest, apply)
|
|
573
|
+
|
|
574
|
+
def op_remove(self, req: dict[str, Any], digest: str) -> dict[str, Any]:
|
|
575
|
+
project = req["project"]
|
|
576
|
+
|
|
577
|
+
def apply() -> dict[str, Any]:
|
|
578
|
+
head = self._cas(project, req["expected_revision"])
|
|
579
|
+
base = self._manifest(project["id"], head)
|
|
580
|
+
updates: dict[str, tuple[str, bool]] = {}
|
|
581
|
+
for p in req["paths"]:
|
|
582
|
+
cur = base.get(p)
|
|
583
|
+
if cur is None or not cur.registered:
|
|
584
|
+
raise RpcError("not_registered", f"{p} is not registered", {"path": p})
|
|
585
|
+
updates[p] = (cur.sha256, False)
|
|
586
|
+
result = self._commit_revision(project["id"], base, head, updates, {}, req)
|
|
587
|
+
return self._with_manifest(project["id"], result)
|
|
588
|
+
|
|
589
|
+
return self.mutate(req, digest, apply)
|
|
590
|
+
|
|
591
|
+
def op_restore(self, req: dict[str, Any], digest: str) -> dict[str, Any]:
|
|
592
|
+
project = req["project"]
|
|
593
|
+
|
|
594
|
+
def apply() -> dict[str, Any]:
|
|
595
|
+
head = self._cas(project, req["expected_revision"])
|
|
596
|
+
base = self._manifest(project["id"], head)
|
|
597
|
+
path, rev = req["path"], req["revision"]
|
|
598
|
+
cur = base.get(path)
|
|
599
|
+
if cur is None or not cur.registered:
|
|
600
|
+
raise RpcError(
|
|
601
|
+
"not_registered",
|
|
602
|
+
f"{path} is not currently registered; re-register it with 'offgit add' first",
|
|
603
|
+
{"path": path},
|
|
604
|
+
)
|
|
605
|
+
if rev > head:
|
|
606
|
+
raise RpcError("revision_not_found", f"revision {rev} does not exist")
|
|
607
|
+
old = self._manifest(project["id"], rev).get(path)
|
|
608
|
+
if old is None or not old.registered:
|
|
609
|
+
raise RpcError("not_found", f"{path} was not registered at revision {rev}")
|
|
610
|
+
result = self._commit_revision(
|
|
611
|
+
project["id"], base, head, {path: (old.sha256, True)}, {}, req
|
|
612
|
+
)
|
|
613
|
+
return self._with_manifest(project["id"], result)
|
|
614
|
+
|
|
615
|
+
return self.mutate(req, digest, apply)
|
|
616
|
+
|
|
617
|
+
def op_settle(self, req: dict[str, Any]) -> dict[str, Any]:
|
|
618
|
+
"""Atomically learn the fate of an earlier request, or make sure it never commits."""
|
|
619
|
+
conn = self.conn
|
|
620
|
+
target = req["target_request_id"]
|
|
621
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
622
|
+
try:
|
|
623
|
+
if req["expected_server_epoch"] != self.server_epoch:
|
|
624
|
+
raise RpcError(
|
|
625
|
+
"epoch_mismatch",
|
|
626
|
+
"server epoch changed; client must rebaseline",
|
|
627
|
+
{"server_epoch": self.server_epoch},
|
|
628
|
+
)
|
|
629
|
+
row = conn.execute(
|
|
630
|
+
"SELECT request_digest, response_json, project_id FROM requests WHERE request_id=?",
|
|
631
|
+
(target,),
|
|
632
|
+
).fetchone()
|
|
633
|
+
if row is None:
|
|
634
|
+
conn.execute(
|
|
635
|
+
"INSERT INTO requests(request_id, project_id, operation, request_digest, "
|
|
636
|
+
"response_json, created_at) VALUES (?, ?, 'settle', ?, '{}', ?)",
|
|
637
|
+
(target, req["project"]["id"], ABANDONED, utcnow()),
|
|
638
|
+
)
|
|
639
|
+
conn.execute("COMMIT")
|
|
640
|
+
return {"status": "abandoned"}
|
|
641
|
+
digest, response_json, pid = row
|
|
642
|
+
conn.execute("COMMIT")
|
|
643
|
+
if pid != req["project"]["id"]:
|
|
644
|
+
raise RpcError("not_found", "request belongs to a different project")
|
|
645
|
+
if digest == ABANDONED:
|
|
646
|
+
return {"status": "abandoned"}
|
|
647
|
+
return {
|
|
648
|
+
"status": "committed",
|
|
649
|
+
"request_digest": digest,
|
|
650
|
+
"response": json.loads(response_json),
|
|
651
|
+
}
|
|
652
|
+
except BaseException:
|
|
653
|
+
if conn.in_transaction:
|
|
654
|
+
conn.execute("ROLLBACK")
|
|
655
|
+
raise
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
__all__ = ["Entry", "RpcError", "Store", "StoreError"]
|