blaym-notebook 0.1.0a1__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.
- blaym_notebook/__init__.py +0 -0
- blaym_notebook/api/__init__.py +12 -0
- blaym_notebook/api/bound.py +91 -0
- blaym_notebook/api/codec.py +63 -0
- blaym_notebook/api/dispatch.py +366 -0
- blaym_notebook/api/errors.py +21 -0
- blaym_notebook/api/routes.py +75 -0
- blaym_notebook/api/stream.py +86 -0
- blaym_notebook/history/__init__.py +11 -0
- blaym_notebook/history/apply.py +490 -0
- blaym_notebook/history/lineage.py +127 -0
- blaym_notebook/history/log.py +94 -0
- blaym_notebook/history/outline.py +150 -0
- blaym_notebook/history/rebuild.py +134 -0
- blaym_notebook/history/snapshots.py +60 -0
- blaym_notebook/local.py +52 -0
- blaym_notebook/ports/__init__.py +29 -0
- blaym_notebook/ports/auth.py +11 -0
- blaym_notebook/ports/blobs.py +182 -0
- blaym_notebook/ports/clock.py +20 -0
- blaym_notebook/ports/events.py +119 -0
- blaym_notebook/ports/search.py +62 -0
- blaym_notebook/privacy/__init__.py +5 -0
- blaym_notebook/privacy/kinds.py +5 -0
- blaym_notebook/privacy/redact.py +317 -0
- blaym_notebook/recording/__init__.py +6 -0
- blaym_notebook/recording/edges.py +45 -0
- blaym_notebook/recording/identity.py +59 -0
- blaym_notebook/recording/ids.py +12 -0
- blaym_notebook/recording/metadata-policy.json +21 -0
- blaym_notebook/recording/metadata.py +73 -0
- blaym_notebook/recording/outputs.py +371 -0
- blaym_notebook/recording/outside.py +200 -0
- blaym_notebook/recording/ports.py +76 -0
- blaym_notebook/recording/registry.py +362 -0
- blaym_notebook/recording/registry_store.py +81 -0
- blaym_notebook/recording/renames.py +33 -0
- blaym_notebook/recording/runs.py +688 -0
- blaym_notebook/recording/scheduler.py +105 -0
- blaym_notebook/recording/searchtext.py +168 -0
- blaym_notebook/recording/sink.py +389 -0
- blaym_notebook/recording/watcher.py +266 -0
- blaym_notebook/service/__init__.py +2 -0
- blaym_notebook/service/auth.py +22 -0
- blaym_notebook/service/blobrefs.py +25 -0
- blaym_notebook/service/core.py +884 -0
- blaym_notebook/service/hydrate.py +69 -0
- blaym_notebook/service/indexing.py +132 -0
- blaym_notebook/service/lease.py +40 -0
- blaym_notebook/service/notify.py +37 -0
- blaym_notebook/service/recovery.py +107 -0
- blaym_notebook/service/revisions.py +86 -0
- blaym_notebook/service/timeline.py +98 -0
- blaym_notebook/store/__init__.py +5 -0
- blaym_notebook/store/blobs.py +208 -0
- blaym_notebook/store/db.py +168 -0
- blaym_notebook/store/events.py +186 -0
- blaym_notebook/store/search.py +113 -0
- blaym_notebook/viewer_static/index.html +13 -0
- blaym_notebook/viewer_static/viewer.css +1 -0
- blaym_notebook/viewer_static/viewer.js +14 -0
- blaym_notebook-0.1.0a1.dist-info/METADATA +31 -0
- blaym_notebook-0.1.0a1.dist-info/RECORD +66 -0
- blaym_notebook-0.1.0a1.dist-info/WHEEL +4 -0
- blaym_notebook-0.1.0a1.dist-info/licenses/LICENSE +202 -0
- blaym_notebook-0.1.0a1.dist-info/licenses/NOTICE +10 -0
|
File without changes
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""The framework-free service API.
|
|
2
|
+
|
|
3
|
+
`handle(request, credential, recording)` maps one HTTP-shaped request to `Service` and
|
|
4
|
+
`Registry` calls and answers an `ApiResponse`. It imports the standard library, the contracts,
|
|
5
|
+
`service`, `ports` (the blob errors) and `recording`; never a web framework, never a store.
|
|
6
|
+
A Jupyter handler (`adapters/jupyter`) and, later, a standalone process both call it.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .dispatch import ApiRequest, ApiResponse, Recording, handle
|
|
10
|
+
from .routes import BASE_PATH, ROUTES, Route
|
|
11
|
+
|
|
12
|
+
__all__ = ["ApiRequest", "ApiResponse", "BASE_PATH", "ROUTES", "Recording", "Route", "handle"]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""The service with a credential bound, for the in-process recorders."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Iterable
|
|
6
|
+
|
|
7
|
+
from blaym_notebook_types import (
|
|
8
|
+
IngestRequest,
|
|
9
|
+
IngestResponse,
|
|
10
|
+
OpenGap,
|
|
11
|
+
OutlineRequest,
|
|
12
|
+
PutBlobResponse,
|
|
13
|
+
ResolveCellRevisionRequest,
|
|
14
|
+
ResolveCellRevisionResponse,
|
|
15
|
+
StateAtRequest,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from blaym_notebook.recording.outside import TipCell
|
|
19
|
+
from blaym_notebook.recording.watcher import StateSource
|
|
20
|
+
from blaym_notebook.service.core import Service
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BoundIngestor:
|
|
24
|
+
"""The service with the credential bound: the `Ingestor` of the in-process recorders."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, service: Service, credential: Any):
|
|
27
|
+
self._s, self._c = service, credential
|
|
28
|
+
|
|
29
|
+
def ingest(self, request: IngestRequest) -> IngestResponse:
|
|
30
|
+
return self._s.ingest(self._c, request)
|
|
31
|
+
|
|
32
|
+
def put_blob(self, exploration_id: str, data: bytes | Iterable[bytes]) -> PutBlobResponse:
|
|
33
|
+
return self._s.put_blob(self._c, exploration_id, data)
|
|
34
|
+
|
|
35
|
+
def resolve_cell_revision(self, request: ResolveCellRevisionRequest) -> ResolveCellRevisionResponse:
|
|
36
|
+
return self._s.resolve_cell_revision(self._c, request)
|
|
37
|
+
|
|
38
|
+
def cell_revisions(self, exploration_id: str) -> dict[str, int]:
|
|
39
|
+
return self._s.cell_revisions(self._c, exploration_id)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class ServiceProbe:
|
|
43
|
+
"""The heartbeat's view of committed state (`StateProbe`), read from the service.
|
|
44
|
+
|
|
45
|
+
The branch read is the one holding the newest tick: until branch switching exists that is
|
|
46
|
+
the branch being recorded."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, service: Service, credential: Any):
|
|
49
|
+
self._s, self._c = service, credential
|
|
50
|
+
|
|
51
|
+
def tip(self, exploration_id: str):
|
|
52
|
+
"""The state at the newest tick, or None before any history exists."""
|
|
53
|
+
outline = self._s.outline(self._c, OutlineRequest(explorationId=exploration_id))
|
|
54
|
+
if outline is None:
|
|
55
|
+
return None
|
|
56
|
+
branch = next((b.branchId for b in outline.branches
|
|
57
|
+
if b.ownTicks and max(t.root for t in b.ownTicks) == outline.highestTick),
|
|
58
|
+
outline.rootBranchId)
|
|
59
|
+
result = self._s.state_at(self._c, StateAtRequest(
|
|
60
|
+
explorationId=exploration_id, branchId=branch, tick=outline.highestTick))
|
|
61
|
+
return getattr(result, "state", None)
|
|
62
|
+
|
|
63
|
+
def runs_open(self, exploration_id: str) -> int:
|
|
64
|
+
state = self.tip(exploration_id)
|
|
65
|
+
return 0 if state is None else sum(1 for r in state.runs if r.status.root == "running")
|
|
66
|
+
|
|
67
|
+
def cell_revisions(self, exploration_id: str) -> dict[str, int]:
|
|
68
|
+
return self._s.cell_revisions(self._c, exploration_id)
|
|
69
|
+
|
|
70
|
+
def open_gaps(self, exploration_id: str) -> list[OpenGap]:
|
|
71
|
+
state = self.tip(exploration_id)
|
|
72
|
+
if state is None:
|
|
73
|
+
return []
|
|
74
|
+
return [OpenGap(gapId=g.gapId, source=g.source, reason=g.reason)
|
|
75
|
+
for g in state.gaps if g.endedTick is None]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def state_source(service: Service, credential: Any) -> StateSource:
|
|
79
|
+
"""Cell revisions and the tip's cells from the service, for the file watcher (the tip is
|
|
80
|
+
None before any history exists)."""
|
|
81
|
+
|
|
82
|
+
def source(nb_id: str):
|
|
83
|
+
probe = ServiceProbe(service, credential)
|
|
84
|
+
state = probe.tip(nb_id)
|
|
85
|
+
if state is None:
|
|
86
|
+
return {}, None
|
|
87
|
+
tip = [TipCell(c["cellId"], c["cellType"], c["code"])
|
|
88
|
+
for c in state.model_dump(mode="json")["notebook"]["cells"]]
|
|
89
|
+
return probe.cell_revisions(nb_id), tip
|
|
90
|
+
|
|
91
|
+
return source
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""JSON in and out of the generated contract models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Iterable, Mapping, TypeVar
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ValidationError
|
|
9
|
+
|
|
10
|
+
from .errors import BadRequest
|
|
11
|
+
|
|
12
|
+
M = TypeVar("M", bound=BaseModel)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def first_error(exc: ValidationError) -> str:
|
|
16
|
+
"""The first validation problem as `where: message`, never the offending value."""
|
|
17
|
+
err = exc.errors(include_input=False, include_url=False)[0]
|
|
18
|
+
where = ".".join(str(p) for p in err.get("loc", ())) or "body"
|
|
19
|
+
return f"{where}: {err.get('msg', 'invalid')}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def body_bytes(body: bytes | Iterable[bytes]) -> bytes:
|
|
23
|
+
return body if isinstance(body, (bytes, bytearray)) else b"".join(body)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse(model: type[M], body: bytes | Iterable[bytes]) -> M:
|
|
27
|
+
"""A request body as `model`; `BadRequest` with the first error otherwise."""
|
|
28
|
+
try:
|
|
29
|
+
data = json.loads(body_bytes(body))
|
|
30
|
+
except (ValueError, RecursionError): # deeply nested JSON raises RecursionError
|
|
31
|
+
raise BadRequest("the body is not valid JSON") from None
|
|
32
|
+
return from_mapping(model, data)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def from_mapping(model: type[M], data: Any) -> M:
|
|
36
|
+
try:
|
|
37
|
+
return model.model_validate(data)
|
|
38
|
+
except ValidationError as exc:
|
|
39
|
+
raise BadRequest(first_error(exc)) from None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def dump(value: Any) -> bytes:
|
|
43
|
+
"""A model, or a plain JSON value, as compact JSON bytes."""
|
|
44
|
+
if isinstance(value, BaseModel):
|
|
45
|
+
return value.model_dump_json(exclude_none=True).encode("utf-8")
|
|
46
|
+
return json.dumps(value, separators=(",", ":")).encode("utf-8")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def int_param(query: Mapping[str, str], name: str) -> int:
|
|
50
|
+
raw = query.get(name)
|
|
51
|
+
if raw is None:
|
|
52
|
+
raise BadRequest(f"{name}: required query parameter")
|
|
53
|
+
try:
|
|
54
|
+
return int(raw)
|
|
55
|
+
except ValueError:
|
|
56
|
+
raise BadRequest(f"{name}: must be an integer") from None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def str_param(query: Mapping[str, str], name: str) -> str:
|
|
60
|
+
raw = query.get(name)
|
|
61
|
+
if not raw:
|
|
62
|
+
raise BadRequest(f"{name}: required query parameter")
|
|
63
|
+
return raw
|
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
"""`handle`: one request in, one answer out. No web framework, no logging of bodies."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from importlib import resources
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any, Callable, Iterable, Mapping
|
|
10
|
+
from urllib.parse import unquote
|
|
11
|
+
|
|
12
|
+
from blaym_notebook_types import (
|
|
13
|
+
CreateBranchRequest,
|
|
14
|
+
EventsBetweenRequest,
|
|
15
|
+
EventsSinceRequest,
|
|
16
|
+
GetBlobRequest,
|
|
17
|
+
IngestRefused,
|
|
18
|
+
IngestRequest,
|
|
19
|
+
IngestResponse,
|
|
20
|
+
NotebookRegistration,
|
|
21
|
+
NotebookRenameRequest,
|
|
22
|
+
NotebookSaveNotice,
|
|
23
|
+
OutlineRequest,
|
|
24
|
+
PrepareOutputsRequest,
|
|
25
|
+
PrepareOutputsResponse,
|
|
26
|
+
RenameBranchRequest,
|
|
27
|
+
ResolveCellRevisionRequest,
|
|
28
|
+
SearchRequest,
|
|
29
|
+
SetActiveBranchRequest,
|
|
30
|
+
StateAtRequest,
|
|
31
|
+
TimelineIndexRequest,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
from blaym_notebook.ports.blobs import BlobCorrupt, BlobNotFound
|
|
35
|
+
from blaym_notebook.recording.edges import startup_gap
|
|
36
|
+
from blaym_notebook.recording.outputs import OutputLimits, item_from_output
|
|
37
|
+
from blaym_notebook.recording.ports import Clock, Ids, SaveNotices
|
|
38
|
+
from blaym_notebook.recording.registry import Registry
|
|
39
|
+
from blaym_notebook.recording.renames import record_rename
|
|
40
|
+
from blaym_notebook.recording.runs import WriteSink
|
|
41
|
+
from blaym_notebook.service.auth import Unauthorized
|
|
42
|
+
from blaym_notebook.service.core import Service, ServiceBusy, UnknownHistory
|
|
43
|
+
|
|
44
|
+
from . import codec
|
|
45
|
+
from .errors import ApiError, BadRequest
|
|
46
|
+
from .routes import match
|
|
47
|
+
|
|
48
|
+
JSON = "application/json"
|
|
49
|
+
CHUNK = 1 << 20
|
|
50
|
+
RETRY_AFTER_S = "1"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class ApiRequest:
|
|
55
|
+
"""`path` is relative to the API base (`/ingest`); `query` and `headers` are plain dicts
|
|
56
|
+
(header names lower case); `body` is bytes, or chunks for a streamed upload."""
|
|
57
|
+
|
|
58
|
+
method: str
|
|
59
|
+
path: str
|
|
60
|
+
query: Mapping[str, str] = field(default_factory=dict)
|
|
61
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
62
|
+
body: bytes | Iterable[bytes] = b""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class ApiResponse:
|
|
67
|
+
status: int
|
|
68
|
+
body: bytes = b""
|
|
69
|
+
headers: Mapping[str, str] = field(default_factory=dict)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class Recording:
|
|
74
|
+
"""What the dispatcher serves: the service and the notebook registry (and the output limits
|
|
75
|
+
`prepare_outputs` builds items with)."""
|
|
76
|
+
|
|
77
|
+
service: Service
|
|
78
|
+
registry: Registry
|
|
79
|
+
output_limits: OutputLimits = field(default_factory=OutputLimits)
|
|
80
|
+
# Optional parts for an editor with no contents hooks of its own (the Jupyter host leaves them unset):
|
|
81
|
+
# the rename route needs `sink`, `clock` and `ids`; the save route needs `files`.
|
|
82
|
+
sink: WriteSink | None = None
|
|
83
|
+
clock: Clock | None = None
|
|
84
|
+
ids: Ids | None = None
|
|
85
|
+
files: SaveNotices | None = None
|
|
86
|
+
editor: str | None = None # the editor the host records renames as
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _json(status: int, value: Any, headers: Mapping[str, str] | None = None) -> ApiResponse:
|
|
90
|
+
return ApiResponse(status, codec.dump(value), {"Content-Type": JSON, **(headers or {})})
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _error(exc: ApiError) -> ApiResponse:
|
|
94
|
+
return _json(exc.status, {"error": exc.message, **exc.extra}, exc.headers)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
MAX_JSON_BODY_BYTES = 64 * 1024 * 1024 # every route but blob upload
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def handle(request: ApiRequest, credential: Any, recording: Recording) -> ApiResponse:
|
|
101
|
+
"""Never raises for a bad request, a bad credential, an unknown history or a busy store."""
|
|
102
|
+
try:
|
|
103
|
+
route, params, allowed = match(request.method.upper(), request.path)
|
|
104
|
+
if route is None:
|
|
105
|
+
if allowed:
|
|
106
|
+
raise ApiError(405, "method not allowed", {"Allow": ", ".join(allowed)})
|
|
107
|
+
raise ApiError(404, "no such route")
|
|
108
|
+
if route.name != "put_blob" and isinstance(request.body, (bytes, bytearray)) \
|
|
109
|
+
and len(request.body) > MAX_JSON_BODY_BYTES:
|
|
110
|
+
raise ApiError(413, "the request body is too large")
|
|
111
|
+
recording.service.info(credential) # the sign-in check, before any route (registry routes never reach the service)
|
|
112
|
+
return _HANDLERS[route.name](request, params, credential, recording)
|
|
113
|
+
except ApiError as exc:
|
|
114
|
+
return _error(exc)
|
|
115
|
+
except Unauthorized:
|
|
116
|
+
return _json(401, {"error": "not signed in"})
|
|
117
|
+
except UnknownHistory:
|
|
118
|
+
return _json(404, {"error": "unknown history or branch"})
|
|
119
|
+
except BlobNotFound:
|
|
120
|
+
return _json(404, {"error": "not found"})
|
|
121
|
+
except BlobCorrupt:
|
|
122
|
+
return _json(500, {"error": "the stored blob is damaged"})
|
|
123
|
+
except ServiceBusy as busy:
|
|
124
|
+
outcomes = [o.model_dump(mode="json", exclude_none=True) for o in (busy.outcomes or [])]
|
|
125
|
+
return _json(503, {"error": "the store is busy", "outcomes": outcomes}, {"Retry-After": RETRY_AFTER_S})
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# -- routes ----------------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _ingest(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
132
|
+
body = codec.parse(IngestRequest, req.body)
|
|
133
|
+
if rec.registry.gate_ingest(body.instanceId, body.explorationId) != "ok":
|
|
134
|
+
detail = "another recorder instance is active for this notebook"
|
|
135
|
+
refused = [IngestRefused(status="refused", eventId=str(ev.root.eventId), reason="not_active_recorder",
|
|
136
|
+
detail=detail) for ev in body.events]
|
|
137
|
+
return _json(200, IngestResponse(apiVersion=1, outcomes=refused))
|
|
138
|
+
response = rec.service.ingest(cred, body)
|
|
139
|
+
_startup_gap(cred, body, response, rec)
|
|
140
|
+
return _json(200, response)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _startup_gap(cred, body: IngestRequest, response, rec: Recording) -> None:
|
|
144
|
+
"""O7: after the first snapshot of a session whose predecessor did not close cleanly, one closed
|
|
145
|
+
gap (source `browser`) says edits may have been lost. Never on a clean reopen."""
|
|
146
|
+
nb = body.explorationId
|
|
147
|
+
if not rec.registry.startup_unclean(nb):
|
|
148
|
+
return
|
|
149
|
+
taken = [o.root.status == "accepted" and ev.root.type == "notebook_snapshot"
|
|
150
|
+
for ev, o in zip(body.events, response.outcomes)]
|
|
151
|
+
if not any(taken):
|
|
152
|
+
return
|
|
153
|
+
events = startup_gap(nb, at_ms=int(time.time() * 1000), editor=body.editor, origin_id=body.instanceId)
|
|
154
|
+
gap = IngestRequest.model_validate({
|
|
155
|
+
"explorationId": nb, "editor": body.editor, "instanceId": body.instanceId,
|
|
156
|
+
**({"targetBranchId": body.targetBranchId} if body.targetBranchId else {}), "events": events})
|
|
157
|
+
rec.service.ingest(cred, gap)
|
|
158
|
+
rec.registry.startup_gap_written(nb) # only after the gap is in: a ServiceBusy keeps the flag
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _put_blob(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
162
|
+
data = req.body
|
|
163
|
+
if isinstance(data, (bytes, bytearray)):
|
|
164
|
+
view = memoryview(bytes(data))
|
|
165
|
+
data = (bytes(view[i:i + CHUNK]) for i in range(0, len(view), CHUNK))
|
|
166
|
+
try:
|
|
167
|
+
return _json(200, rec.service.put_blob(cred, params["explorationId"], data))
|
|
168
|
+
except ValueError:
|
|
169
|
+
raise BadRequest("explorationId: not a valid history id") from None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _prepare_outputs(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
173
|
+
body = codec.parse(PrepareOutputsRequest, req.body)
|
|
174
|
+
items = []
|
|
175
|
+
for index, output in enumerate(body.outputs):
|
|
176
|
+
try:
|
|
177
|
+
prepared = item_from_output(output, rec.output_limits)
|
|
178
|
+
except ValueError:
|
|
179
|
+
raise BadRequest(f"outputs.{index}: not a notebook output") from None
|
|
180
|
+
item = prepared.item
|
|
181
|
+
if prepared.blob is not None:
|
|
182
|
+
stored = rec.service.put_blob(cred, body.explorationId, prepared.blob)
|
|
183
|
+
item = item.model_copy(update={"contentHash": stored.contentHash})
|
|
184
|
+
items.append(item)
|
|
185
|
+
return _json(200, PrepareOutputsResponse(apiVersion=1, items=items))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _resolve(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
189
|
+
body = codec.parse(ResolveCellRevisionRequest, req.body)
|
|
190
|
+
return _json(200, rec.service.resolve_cell_revision(cred, body))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _register(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
194
|
+
return _json(200, rec.registry.register(codec.parse(NotebookRegistration, req.body)))
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _status(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
198
|
+
return _json(200, rec.registry.status(params["notebookId"], codec.str_param(req.query, "instanceId")))
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _close(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
202
|
+
try:
|
|
203
|
+
data = json.loads(codec.body_bytes(req.body))
|
|
204
|
+
except (ValueError, RecursionError):
|
|
205
|
+
raise BadRequest("the body is not valid JSON") from None
|
|
206
|
+
for key in ("notebookId", "instanceId"):
|
|
207
|
+
if not isinstance(data, dict) or not isinstance(data.get(key), str) or not data[key]:
|
|
208
|
+
raise BadRequest(f"{key}: required string")
|
|
209
|
+
rec.registry.close(data["notebookId"], data["instanceId"])
|
|
210
|
+
return ApiResponse(204)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _only_active(rec: Recording, notebook_id: str, instance_id: str) -> None:
|
|
214
|
+
if rec.registry.gate_ingest(instance_id, notebook_id) != "ok":
|
|
215
|
+
raise ApiError(409, "another recorder instance is active for this notebook")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _rename(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
219
|
+
body = codec.parse(NotebookRenameRequest, req.body)
|
|
220
|
+
if rec.sink is None or rec.clock is None or rec.ids is None or rec.editor is None:
|
|
221
|
+
raise ApiError(404, "not_supported_here")
|
|
222
|
+
_only_active(rec, body.notebookId, body.instanceId)
|
|
223
|
+
record_rename(rec.registry, rec.sink, rec.clock, rec.ids, body.oldPath, body.newPath,
|
|
224
|
+
editor=rec.editor, origin_id=body.instanceId)
|
|
225
|
+
return _json(200, rec.registry.status(body.notebookId, body.instanceId))
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _save(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
229
|
+
body = codec.parse(NotebookSaveNotice, req.body)
|
|
230
|
+
if rec.files is None:
|
|
231
|
+
raise ApiError(404, "not_supported_here")
|
|
232
|
+
_only_active(rec, body.notebookId, body.instanceId)
|
|
233
|
+
(rec.files.save_started if body.phase.value == "started" else rec.files.save_finished)(body.path)
|
|
234
|
+
return ApiResponse(204)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _info(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
238
|
+
return _json(200, rec.service.info(cred))
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _state(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
242
|
+
request = codec.from_mapping(StateAtRequest, {
|
|
243
|
+
"explorationId": codec.str_param(req.query, "explorationId"),
|
|
244
|
+
"branchId": codec.str_param(req.query, "branchId"),
|
|
245
|
+
"tick": codec.int_param(req.query, "tick")})
|
|
246
|
+
return _json(200, rec.service.state_at(cred, request))
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _outline(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
250
|
+
request = codec.from_mapping(OutlineRequest, {"explorationId": codec.str_param(req.query, "explorationId")})
|
|
251
|
+
outline = rec.service.outline(cred, request)
|
|
252
|
+
if outline is None:
|
|
253
|
+
raise UnknownHistory("this history does not exist")
|
|
254
|
+
return _json(200, outline)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _events_since(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
258
|
+
request = codec.from_mapping(EventsSinceRequest, {
|
|
259
|
+
"explorationId": codec.str_param(req.query, "explorationId"),
|
|
260
|
+
"branchId": codec.str_param(req.query, "branchId"),
|
|
261
|
+
"afterTick": codec.int_param(req.query, "afterTick")})
|
|
262
|
+
return _json(200, rec.service.events_since(cred, request))
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _optional_ints(req: ApiRequest, *names: str) -> dict[str, int]:
|
|
266
|
+
return {n: codec.int_param(req.query, n) for n in names if req.query.get(n)}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _timeline(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
270
|
+
request = codec.from_mapping(TimelineIndexRequest, {
|
|
271
|
+
"explorationId": codec.str_param(req.query, "explorationId"),
|
|
272
|
+
"branchId": codec.str_param(req.query, "branchId"),
|
|
273
|
+
**_optional_ints(req, "fromTick", "toTick", "limit")})
|
|
274
|
+
return _json(200, rec.service.timeline_index(cred, request))
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _events_between(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
278
|
+
request = codec.from_mapping(EventsBetweenRequest, {
|
|
279
|
+
"explorationId": codec.str_param(req.query, "explorationId"),
|
|
280
|
+
"branchId": codec.str_param(req.query, "branchId"),
|
|
281
|
+
"fromTick": codec.int_param(req.query, "fromTick"),
|
|
282
|
+
"toTick": codec.int_param(req.query, "toTick"),
|
|
283
|
+
**_optional_ints(req, "maxEvents")})
|
|
284
|
+
return _json(200, rec.service.events_between(cred, request))
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _search(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
288
|
+
data: dict[str, Any] = {"explorationId": codec.str_param(req.query, "explorationId"),
|
|
289
|
+
"query": codec.str_param(req.query, "query")}
|
|
290
|
+
if req.query.get("kinds"):
|
|
291
|
+
data["kinds"] = req.query["kinds"].split(",")
|
|
292
|
+
if req.query.get("limit"):
|
|
293
|
+
data["limit"] = codec.int_param(req.query, "limit")
|
|
294
|
+
return _json(200, rec.service.search(cred, codec.from_mapping(SearchRequest, data)))
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _create_branch(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
298
|
+
"""A refusal is the service's answer (status 200), not an HTTP error."""
|
|
299
|
+
return _json(200, rec.service.create_branch(cred, codec.parse(CreateBranchRequest, req.body)))
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _rename_branch(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
303
|
+
return _json(200, rec.service.rename_branch(cred, codec.parse(RenameBranchRequest, req.body)))
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _set_active_branch(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
307
|
+
return _json(200, rec.service.set_active_branch(cred, codec.parse(SetActiveBranchRequest, req.body)))
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _get_blob(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
311
|
+
request = codec.from_mapping(GetBlobRequest, params)
|
|
312
|
+
try:
|
|
313
|
+
data = rec.service.get_blob(cred, request)
|
|
314
|
+
except ValueError:
|
|
315
|
+
raise BadRequest("explorationId or contentHash: not valid") from None
|
|
316
|
+
return ApiResponse(200, data, {"Content-Type": "application/octet-stream"})
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _stream(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
320
|
+
raise ApiError(501, "the stream is served by the host, not as a JSON answer")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
_VIEWER_FILES = ("index.html", "viewer.js", "viewer.css")
|
|
324
|
+
_CONTENT_TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8",
|
|
325
|
+
".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png",
|
|
326
|
+
".json": "application/json", ".woff2": "font/woff2"}
|
|
327
|
+
_VIEWER_CSP = ("default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; "
|
|
328
|
+
"connect-src 'self'; frame-ancestors 'self'")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _viewer_asset(req: ApiRequest, params, cred, rec: Recording) -> ApiResponse:
|
|
332
|
+
"""A built page file by name: only allow-listed names (the fixed three, plus any the build lists
|
|
333
|
+
in `manifest.json`), so no path reaches the disk. The page holds no secret; the sign-in check
|
|
334
|
+
in `handle` still runs, as for every route."""
|
|
335
|
+
folder = resources.files("blaym_notebook").joinpath("viewer_static")
|
|
336
|
+
name = unquote(params["name"])
|
|
337
|
+
allowed = set(_VIEWER_FILES)
|
|
338
|
+
manifest = folder.joinpath("manifest.json")
|
|
339
|
+
if manifest.is_file():
|
|
340
|
+
try:
|
|
341
|
+
listed = json.loads(manifest.read_bytes())
|
|
342
|
+
allowed.update(n for n in listed if isinstance(n, str))
|
|
343
|
+
except (ValueError, TypeError):
|
|
344
|
+
pass
|
|
345
|
+
ext = "." + name.rsplit(".", 1)[-1] if "." in name else ""
|
|
346
|
+
if name not in allowed or "/" in name or "\\" in name or ext not in _CONTENT_TYPES \
|
|
347
|
+
or not folder.joinpath(name).is_file():
|
|
348
|
+
raise ApiError(404, "no such file")
|
|
349
|
+
headers = {"Content-Type": _CONTENT_TYPES[ext], "Cache-Control": "no-cache",
|
|
350
|
+
"X-Content-Type-Options": "nosniff"}
|
|
351
|
+
if name == "index.html":
|
|
352
|
+
headers["Content-Security-Policy"] = _VIEWER_CSP
|
|
353
|
+
return ApiResponse(200, folder.joinpath(name).read_bytes(), headers)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
_HANDLERS: dict[str, Callable[..., ApiResponse]] = {
|
|
357
|
+
"ingest": _ingest, "put_blob": _put_blob, "prepare_outputs": _prepare_outputs,
|
|
358
|
+
"resolve_cell_revision": _resolve, "register": _register, "status": _status, "close": _close,
|
|
359
|
+
"rename": _rename, "save": _save,
|
|
360
|
+
"info": _info, "state": _state, "outline": _outline, "events_since": _events_since,
|
|
361
|
+
"timeline": _timeline, "events_between": _events_between,
|
|
362
|
+
"search": _search, "create_branch": _create_branch, "set_active_branch": _set_active_branch,
|
|
363
|
+
"rename_branch": _rename_branch,
|
|
364
|
+
"get_blob": _get_blob, "stream": _stream,
|
|
365
|
+
"viewer_asset": _viewer_asset,
|
|
366
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Errors the dispatcher turns into HTTP answers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ApiError(Exception):
|
|
7
|
+
"""An answer that is not a success: a status, a short message and optional headers.
|
|
8
|
+
The message never contains request content (it may hold secrets)."""
|
|
9
|
+
|
|
10
|
+
def __init__(self, status: int, message: str, headers: dict[str, str] | None = None,
|
|
11
|
+
extra: dict | None = None):
|
|
12
|
+
super().__init__(message)
|
|
13
|
+
self.status = status
|
|
14
|
+
self.message = message
|
|
15
|
+
self.headers = headers or {}
|
|
16
|
+
self.extra = extra or {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class BadRequest(ApiError):
|
|
20
|
+
def __init__(self, message: str):
|
|
21
|
+
super().__init__(400, message)
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""The route table (S5, section 3). One place: the dispatcher reads it, a test writes it to
|
|
2
|
+
`fixtures/api/routes.json`, and the TypeScript side checks that file, so the two cannot drift.
|
|
3
|
+
|
|
4
|
+
Paths are relative to `<base_url>/blaym-jupyter/api` and use `{name}` for one path segment.
|
|
5
|
+
`request` and `response` name the contract types (`query` means query parameters,
|
|
6
|
+
`bytes` means a raw body, `none` an empty one).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
BASE_PATH = "blaym-jupyter/api"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Route:
|
|
19
|
+
name: str
|
|
20
|
+
method: str
|
|
21
|
+
path: str
|
|
22
|
+
request: str
|
|
23
|
+
response: str
|
|
24
|
+
|
|
25
|
+
def regex(self) -> re.Pattern[str]:
|
|
26
|
+
return re.compile("^" + re.sub(r"\{(\w+)\}", r"(?P<\1>[^/]+)", self.path) + "$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
ROUTES: tuple[Route, ...] = (
|
|
30
|
+
Route("ingest", "POST", "/ingest", "IngestRequest", "IngestResponse"),
|
|
31
|
+
Route("put_blob", "PUT", "/blobs/{explorationId}", "bytes", "PutBlobResponse"),
|
|
32
|
+
Route("prepare_outputs", "POST", "/outputs/prepare", "PrepareOutputsRequest", "PrepareOutputsResponse"),
|
|
33
|
+
Route("resolve_cell_revision", "POST", "/cells/revision", "ResolveCellRevisionRequest",
|
|
34
|
+
"ResolveCellRevisionResponse"),
|
|
35
|
+
Route("register", "POST", "/notebooks/register", "NotebookRegistration", "NotebookStatus"),
|
|
36
|
+
Route("status", "GET", "/notebooks/{notebookId}/status", "query:instanceId", "NotebookStatus"),
|
|
37
|
+
Route("close", "POST", "/notebooks/close", "json:notebookId,instanceId", "none"),
|
|
38
|
+
Route("rename", "POST", "/notebooks/rename", "NotebookRenameRequest", "NotebookStatus"),
|
|
39
|
+
Route("save", "POST", "/notebooks/save", "NotebookSaveNotice", "none"),
|
|
40
|
+
Route("info", "GET", "/info", "none", "ServiceInfo"),
|
|
41
|
+
Route("state", "GET", "/state", "query:explorationId,branchId,tick", "RebuildResult"),
|
|
42
|
+
Route("outline", "GET", "/outline", "query:explorationId", "HistoryOutline"),
|
|
43
|
+
Route("events_since", "GET", "/events-since", "query:explorationId,branchId,afterTick", "EventsSinceResponse"),
|
|
44
|
+
Route("timeline", "GET", "/timeline", "query:explorationId,branchId,fromTick?,toTick?,limit?",
|
|
45
|
+
"TimelineIndexResponse"),
|
|
46
|
+
Route("events_between", "GET", "/events-between", "query:explorationId,branchId,fromTick,toTick,maxEvents?",
|
|
47
|
+
"EventsBetweenResponse"),
|
|
48
|
+
Route("search", "GET", "/search", "query:explorationId,query,kinds?,limit?", "SearchResponse"),
|
|
49
|
+
Route("create_branch", "POST", "/branches/create", "CreateBranchRequest", "CreateBranchResponse"),
|
|
50
|
+
Route("set_active_branch", "POST", "/branches/active", "SetActiveBranchRequest", "SetActiveBranchResponse"),
|
|
51
|
+
Route("rename_branch", "POST", "/branches/rename", "RenameBranchRequest", "RenameBranchResponse"),
|
|
52
|
+
Route("get_blob", "GET", "/blobs/{explorationId}/{contentHash}", "none", "bytes"),
|
|
53
|
+
Route("stream", "GET", "/stream", "query:explorationId,afterTick?", "event-stream"),
|
|
54
|
+
Route("viewer_asset", "GET", "/viewer/{name}", "none", "bytes"),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def match(method: str, path: str) -> tuple[Route | None, dict[str, str], list[str]]:
|
|
59
|
+
"""`(route, path parameters, allowed methods)`: no route and no methods is a 404; no route
|
|
60
|
+
with methods is a 405."""
|
|
61
|
+
allowed: list[str] = []
|
|
62
|
+
for route in ROUTES:
|
|
63
|
+
found = route.regex().match(path)
|
|
64
|
+
if found is None:
|
|
65
|
+
continue
|
|
66
|
+
if route.method == method:
|
|
67
|
+
return route, found.groupdict(), []
|
|
68
|
+
allowed.append(route.method)
|
|
69
|
+
return None, {}, allowed
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def as_json() -> dict:
|
|
73
|
+
return {"base": BASE_PATH, "routes": [
|
|
74
|
+
{"name": r.name, "method": r.method, "path": r.path, "request": r.request, "response": r.response}
|
|
75
|
+
for r in ROUTES]}
|