Repository navigation
Expand file tree
/
Copy pathchat_bundle.py
More file actions
417 lines (380 loc) · 14.3 KB
/
Copy pathchat_bundle.py
File metadata and controls
417 lines (380 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/env python3
"""Build, verify and stage Chat assets; generated output never belongs in Git."""
from __future__ import annotations
import argparse
from contextlib import AbstractContextManager
import importlib.util
import json
import os
import re
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import time
from typing import Callable, TypeVar
import zipfile
ROOT = Path(__file__).resolve().parents[1]
# The contract asks the shared digest owner what a stored digest looks like, so loading
# it by file path needs the checkout importable: a source build has no installed LoopX.
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
spec = importlib.util.spec_from_file_location(
"chat_bundle_contract", ROOT / "loopx/presentation/chat_bundle.py"
)
contract = importlib.util.module_from_spec(spec)
spec.loader.exec_module(contract)
OUTPUT = ROOT / "loopx/web/chat"
def previous_assets(previous: Path | None) -> list[str]:
if previous is None:
return []
if (previous / contract.MANIFEST).is_file():
return contract.validate_bundle(previous)["current_assets"]
# Legacy release wheels predate provenance metadata. Include their bounded
# asset directory for this one transition; never load history from Git.
if not (previous / "index.html").is_file():
raise RuntimeError("previous delivery has no index.html")
assets = sorted(
p.relative_to(previous).as_posix()
for p in (previous / "assets").rglob("*")
if p.is_file()
)
entries = re.findall(
r'(?:src|href)="/chat/(assets/[^\"]+)"',
(previous / "index.html").read_text(encoding="utf-8"),
)
if not entries or not set(entries) <= set(assets):
raise RuntimeError("previous delivery has missing entry assets")
return assets
def _build_lock() -> AbstractContextManager[Path]:
from loopx.file_lock import exclusive_file_lock
return exclusive_file_lock(ROOT / ".local/chat-bundle-build", timeout_seconds=300)
def build(previous: Path | None, *, install: bool = False) -> None:
# npm ci and delivery publication share checkout-local mutable directories.
with _build_lock():
_build(previous, install=install)
def _build(previous: Path | None, *, install: bool) -> None:
dashboard = ROOT / "apps/presentation/dashboard"
npm = shutil.which("npm.cmd" if os.name == "nt" else "npm")
if not npm:
raise RuntimeError(
"Node.js/npm is required to build a source checkout; release wheels already contain the frontend"
)
if install:
subprocess.run([npm, "ci", "--ignore-scripts"], cwd=dashboard, check=True)
before = contract.source_inputs(ROOT)
previous_assets(previous) # Reject invalid lineage before spending a build.
OUTPUT.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(
prefix=".chat-build-", dir=OUTPUT.parent
) as temporary:
staged = Path(temporary) / "chat"
subprocess.run(
[npm, "run", "build:chat:vite"],
cwd=dashboard,
env={**os.environ, "LOOPX_CHAT_OUT_DIR": str(staged)},
check=True,
)
current = sorted(
p.relative_to(staged).as_posix()
for p in (staged / "assets").rglob("*")
if p.is_file()
)
if before != contract.source_inputs(ROOT):
raise RuntimeError(
"source changed while building; retry without concurrent edits"
)
finish_delivery(staged, previous, current, before, _source_revision())
print(
"Chat bundle built and verified; current and previous delivery assets retained."
)
def _source_revision() -> str | None:
"""Resolve the built delivery's source revision.
Staged benchmark sources are git archives inside task containers that
often lack a git binary entirely; a missing executable must take the same
environment fallback as a failed rev-parse.
"""
try:
revision = subprocess.run(
["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, text=True
)
except FileNotFoundError:
return os.environ.get("LOOPX_RESOLVED_SOURCE_GIT_COMMIT")
if revision.returncode == 0:
return revision.stdout.strip()
return os.environ.get("LOOPX_RESOLVED_SOURCE_GIT_COMMIT")
def finish_delivery(
staged: Path,
previous: Path | None,
current: list[str],
inputs: dict,
revision: str | None,
) -> None:
old_assets = previous_assets(previous)
for name in old_assets:
source = previous / name
if (
not contract.safe_relative(name)
or not name.startswith("assets/")
or source.is_symlink()
or not source.resolve().is_relative_to(previous.resolve())
):
raise RuntimeError("invalid previous asset")
target = staged / name
if target.exists() and contract.digest(source) != contract.digest(target):
raise RuntimeError(
"same asset name has different content across deliveries"
)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
generations = [current]
if set(old_assets) - set(current):
generations.append(old_assets)
(staged / "asset-retention.json").write_text(
json.dumps(
{
"schema_version": "loopx_chat_asset_retention_v1",
"generations": generations,
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
manifest = {
"schema_version": contract.CHAT_BUNDLE_SCHEMA_VERSION,
"source_revision": revision,
"source_files": inputs,
"current_assets": current,
"files": {
p.relative_to(staged).as_posix(): contract.digest(p)
for p in sorted(staged.rglob("*"))
if p.is_file() and p.name != contract.MANIFEST
},
}
(staged / contract.MANIFEST).write_text(
json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
contract.validate_bundle(staged, source_root=ROOT)
backup = staged.parent / "previous"
if OUTPUT.exists():
OUTPUT.rename(backup)
try:
staged.rename(OUTPUT)
except OSError:
if backup.exists():
backup.rename(OUTPUT)
raise
def ensure(previous: Path | None = None) -> None:
# Keep a qualified, read-only archive usable without creating a lock directory.
try:
contract.validate_bundle(OUTPUT, source_root=ROOT)
if previous is None or previous.resolve() == OUTPUT.resolve():
return
except RuntimeError:
pass
with _build_lock():
_ensure(previous)
def _ensure(previous: Path | None) -> None:
try:
manifest = contract.validate_bundle(OUTPUT, source_root=ROOT)
except RuntimeError:
_build(previous, install=True)
return
if previous is None or previous.resolve() == OUTPUT.resolve():
return
# A bundled desktop/archive install must not need Node or network merely to
# carry forward the currently installed delivery's assets.
with tempfile.TemporaryDirectory(
prefix=".chat-build-", dir=OUTPUT.parent
) as temporary:
staged = Path(temporary) / "chat"
for name in manifest["files"]:
if name.startswith("assets/") and name not in manifest["current_assets"]:
continue
target = staged / name
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(OUTPUT / name, target)
finish_delivery(
staged,
previous,
manifest["current_assets"],
manifest["source_files"],
manifest["source_revision"],
)
_T = TypeVar("_T")
def _retry_gh(
operation: Callable[[], _T],
*,
label: str,
attempts: int = 4,
base_delay: float = 1.0,
before_attempt: Callable[[], None] | None = None,
) -> _T:
"""Retry transient GitHub CLI failures with bounded exponential backoff."""
for attempt in range(1, attempts + 1):
if before_attempt is not None:
before_attempt()
try:
return operation()
except subprocess.CalledProcessError as exc:
if attempt >= attempts:
raise
delay = base_delay * (2 ** (attempt - 1))
print(
f"Retrying {label} after gh exit {exc.returncode} "
f"(attempt {attempt}/{attempts}, sleep {delay:.1f}s)",
file=sys.stderr,
)
time.sleep(delay)
raise AssertionError("unreachable")
def release_build(tag: str, repository: str) -> None:
# Use the preceding published version, never the latest desktop prerelease
# or a future release when rebuilding an older tag.
pages = json.loads(
_retry_gh(
lambda: subprocess.check_output(
[
"gh",
"api",
"--paginate",
"--slurp",
f"repos/{repository}/releases?per_page=100",
],
text=True,
),
label=f"gh release listing for {repository}",
)
)
versions = [
r
for page in pages
for r in page
if not r["draft"]
and not r["prerelease"]
and re.fullmatch(r"v\d+\.\d+\.\d+", r["tag_name"])
]
def number(value: str) -> tuple[int, ...]:
match = re.fullmatch(
r"v(\d+)\.(\d+)\.(\d+)(?:(a|b|rc)(\d+))?",
value,
)
if match is None:
raise ValueError(f"invalid LoopX release tag: {value}")
major, minor, patch, prerelease, prerelease_number = match.groups()
prerelease_rank = {None: 3, "a": 0, "b": 1, "rc": 2}[prerelease]
return (
int(major),
int(minor),
int(patch),
prerelease_rank,
int(prerelease_number or 0),
)
predecessors = [r for r in versions if number(r["tag_name"]) < number(tag)]
if not predecessors:
build(None, install=True)
return
previous = max(predecessors, key=lambda r: number(r["tag_name"]))
wheels = [
a["name"]
for a in previous["assets"]
if a["name"].startswith("loopx-") and a["name"].endswith(".whl")
]
if len(wheels) != 1:
raise RuntimeError("preceding release must contain exactly one LoopX wheel")
with tempfile.TemporaryDirectory(prefix="loopx-previous-release-") as temporary:
root = Path(temporary)
directory = root / "download"
def reset_download_dir() -> None:
shutil.rmtree(directory, ignore_errors=True)
directory.mkdir(parents=True, exist_ok=True)
_retry_gh(
lambda: subprocess.run(
[
"gh",
"release",
"download",
previous["tag_name"],
"--repo",
repository,
"--pattern",
wheels[0],
"--pattern",
"SHA256SUMS",
"--dir",
str(directory),
],
check=True,
),
label=f"gh release download {previous['tag_name']}",
before_attempt=reset_download_dir,
)
checksums = (directory / "SHA256SUMS").read_text().splitlines()
matches = [
line.split()[0]
for line in checksums
if len(line.split()) == 2
and Path(line.split()[1].lstrip("*")).name == wheels[0]
]
if matches != [contract.digest(directory / wheels[0])]:
raise RuntimeError("previous release wheel checksum mismatch")
old_bundle = root / "chat"
extract_wheel(directory / wheels[0], old_bundle)
build(old_bundle, install=True)
def extract_wheel(wheel: Path, destination: Path) -> None:
if destination.exists():
raise RuntimeError("previous bundle destination must not exist")
with zipfile.ZipFile(wheel) as archive:
prefix = "loopx/web/chat/"
entries = [
item
for item in archive.infolist()
if item.filename.startswith(prefix) and not item.is_dir()
]
if len({item.filename for item in entries}) != len(entries):
raise RuntimeError("duplicate previous wheel entries")
if not entries or sum(item.file_size for item in entries) > 128 * 1024 * 1024:
raise RuntimeError("previous wheel has no bounded Chat bundle")
for item in entries:
name = item.filename[len(prefix) :]
if (
not contract.safe_relative(name)
or (item.external_attr >> 16) & 0o170000 == 0o120000
):
raise RuntimeError("invalid previous wheel path")
target = destination / name
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(archive.read(item))
previous_assets(destination)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
b = commands.add_parser("build")
b.add_argument("--previous", type=Path)
b.add_argument("--install", action="store_true")
a = commands.add_parser("ensure")
a.add_argument("--previous", type=Path)
v = commands.add_parser("verify")
v.add_argument("--bundle", type=Path, default=OUTPUT)
v.add_argument("--source", action="store_true")
e = commands.add_parser("extract-wheel")
e.add_argument("wheel", type=Path)
e.add_argument("destination", type=Path)
r = commands.add_parser("release-build")
r.add_argument("--tag", required=True)
r.add_argument("--repo", required=True)
args = parser.parse_args()
if args.command == "build":
build(args.previous, install=args.install)
elif args.command == "ensure":
ensure(args.previous)
elif args.command == "verify":
contract.validate_bundle(args.bundle, source_root=ROOT if args.source else None)
print("Chat bundle verified")
elif args.command == "release-build":
release_build(args.tag, args.repo)
else:
extract_wheel(args.wheel, args.destination)
if __name__ == "__main__":
main()