From 98784337d78566b4c872b682d0feab0eaf1d7503 Mon Sep 17 00:00:00 2001 From: codex-check Date: Sun, 29 Nov 2026 11:53:28 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(checks):=20=E8=AE=A9=E5=A5=91=E7=BA=A6?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E5=8F=AA=E8=AF=BB=E5=B9=B6=E5=A4=8D=E7=94=A8?= =?UTF-8?q?=E9=9D=99=E6=80=81=E9=97=A8=E7=A6=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在临时目录生成 Web 绑定并报告差异 - 让本地、仓库 CI 和发包使用同一静态检查入口 --- .github/workflows/packages-release.yml | 2 +- package.json | 3 ++- runtimes/web/generate-bindings.mjs | 31 ++++++++++++++++++++++++++ runtimes/web/package.json | 4 ++-- 4 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 runtimes/web/generate-bindings.mjs diff --git a/.github/workflows/packages-release.yml b/.github/workflows/packages-release.yml index 3731970..bb210c9 100644 --- a/.github/workflows/packages-release.yml +++ b/.github/workflows/packages-release.yml @@ -138,7 +138,7 @@ jobs: pnpm install --frozen-lockfile - name: Check package contracts before building release assets - run: pnpm contracts:check && pnpm format:check && pnpm lint && pnpm type-check + run: pnpm check:static - name: Verify managed package versions run: | diff --git a/package.json b/package.json index be7aef1..531f42f 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,8 @@ "scripts": { "build": "SOURCE_DATE_EPOCH=315532800 pdm build --no-sdist --dest \"$INIT_CWD/dist\" && SOURCE_DATE_EPOCH=315532800 pdm build --project toolkit --no-sdist --no-clean --dest \"$INIT_CWD/dist\" && SOURCE_DATE_EPOCH=315532800 pdm build --project runtimes/core-py --no-sdist --no-clean --dest \"$INIT_CWD/dist\" && pnpm --filter @inkcre/extension-runtime-web build", "changeset": "changeset", - "check": "pnpm release:check && pnpm web:check && pnpm contracts:check && pnpm format:check && pnpm lint && pnpm type-check && pnpm build && pnpm --filter @inkcre/extension-runtime-web exec node check-boundaries.mjs && pnpm packages:check && pnpm registry:check", + "check": "pnpm release:check && pnpm check:static && pnpm build && pnpm --filter @inkcre/extension-runtime-web exec node check-boundaries.mjs && pnpm packages:check && pnpm registry:check", + "check:static": "pnpm web:check && pnpm contracts:check && pnpm format:check && pnpm lint && pnpm type-check", "packages:check": "pdm run python scripts/check_packages.py", "contracts:check": "pdm run python scripts/generate_contracts.py --check && pdm run python runtimes/core-py/scripts/generate_contracts.py --check && pnpm --filter @inkcre/extension-runtime-web check:bindings", "contracts:generate": "pdm run python scripts/generate_contracts.py && pdm run python runtimes/core-py/scripts/generate_contracts.py && pnpm --filter @inkcre/extension-runtime-web generate:bindings", diff --git a/runtimes/web/generate-bindings.mjs b/runtimes/web/generate-bindings.mjs new file mode 100644 index 0000000..85ef68c --- /dev/null +++ b/runtimes/web/generate-bindings.mjs @@ -0,0 +1,31 @@ +import { execFileSync, spawnSync } from 'node:child_process' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const check = process.argv.includes('--check') +const bindings = 'src/generated' +const output = check ? mkdtempSync(join(tmpdir(), 'inkcre-web-bindings-')) : bindings + +try { + execFileSync('openapi-ts', ['-f', 'openapi-ts.config.ts', '--output', output, '--no-log-file'], { + stdio: 'inherit', + }) + execFileSync('prettier', ['--config', '../../.prettierrc.json', '--write', output], { + stdio: 'inherit', + }) + if (check) { + const diff = spawnSync('git', ['diff', '--no-index', '--name-only', '--', bindings, output], { + stdio: 'inherit', + }) + if (diff.error) throw diff.error + if (diff.status !== 0) { + console.error( + 'Web Runtime bindings differ. Run pnpm contracts:generate at the workspace root.', + ) + process.exitCode = diff.status ?? 1 + } + } +} finally { + if (check) rmSync(output, { recursive: true, force: true }) +} diff --git a/runtimes/web/package.json b/runtimes/web/package.json index 56278db..8b4c414 100644 --- a/runtimes/web/package.json +++ b/runtimes/web/package.json @@ -20,8 +20,8 @@ "prepare": "pnpm build", "build": "tsdown --platform neutral", "check:boundaries": "pnpm build && node check-boundaries.mjs", - "check:bindings": "pnpm generate:bindings && git diff --exit-code -- src/generated", - "generate:bindings": "openapi-ts -f openapi-ts.config.ts && prettier --write src/generated", + "check:bindings": "node generate-bindings.mjs --check", + "generate:bindings": "node generate-bindings.mjs", "type-check": "tsc --noEmit", "pack": "pnpm pack" }, From 5fc683db3f0bcff330a3e7bd4c49723ed56fcf3d Mon Sep 17 00:00:00 2001 From: codex-check Date: Sun, 29 Nov 2026 11:53:28 +0800 Subject: [PATCH 2/2] =?UTF-8?q?ref(verification):=20=E5=9C=A8=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E5=8F=91=E8=A1=8C=E8=BE=B9=E7=95=8C=E6=A0=B8=E9=AA=8C?= =?UTF-8?q?=20Registry=20=E5=92=8C=E5=AE=89=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 强制回放含历史数据的迁移并使用实际上传请求验证发布冲突 - 使用隔离安装的 Toolkit、Runtime、预览目录和标准 pip 验证发行交付 - 删除重复的目录、文档和退役接口形状断言 --- docs/40-deployment/local-development.md | 8 +- runtimes/web/check-boundaries.mjs | 8 +- scripts/check_documentation.py | 4 - scripts/check_installed_runtime.py | 80 +++++ scripts/check_packages.py | 393 ++++++++---------------- scripts/check_registry.py | 129 +++++--- 6 files changed, 311 insertions(+), 311 deletions(-) create mode 100644 scripts/check_installed_runtime.py diff --git a/docs/40-deployment/local-development.md b/docs/40-deployment/local-development.md index ef505c1..01d254f 100644 --- a/docs/40-deployment/local-development.md +++ b/docs/40-deployment/local-development.md @@ -21,13 +21,15 @@ pdm run python -m inkcre_extension_registry 修改模型后运行 `pnpm db:makemigrations`,审查生成的迁移。Tortoise 1.1 的 `CreateModel` 不会把 `Meta.constraints` 写入数据库,因此新表的 CHECK 约束须使用原生 `AddConstraint` 操作显式添加,参照初始迁移;真实 PostgreSQL 的非法数据验收用于防止约束仅存在于模型描述中。`pnpm db:migrate` 只向前执行;上线后只能追加迁移,修复通过后续迁移完成。交付必须以 `MIGRATION_DATABASE_URL` 指定 owner 连接,服务的 `DATABASE_URL` 使用普通 `registry_app`。本地单账号开发仍可省略迁移变量并复用 `DATABASE_URL`。权限迁移创建 NOLOGIN 角色;生产和预览控制器在迁移后通过 `scripts/registry_database.py` 设置独立密码并启用登录。服务不在请求或启动期间迁移。 -完整检查需要空的、一次性的 PostgreSQL 数据库: +`pnpm check:static` 检查源码、样式和生成契约,可以在准备数据库前运行。完整门禁和包发布 CI 复用此入口。绑定校验在临时目录运行生成器,`pnpm contracts:generate` 用于有意更新契约时写回工作树。 + +完整检查需要全新的、一次性的 PostgreSQL 实例: ```bash REGISTRY_TEST_DATABASE_URL=postgres://registry:registry-check@localhost:5432/registry_check pnpm check ``` -CI 创建 PostgreSQL 17 service;本地使用独立、一次性的 PostgreSQL 实例或 Neon 测试分支。授权迁移会创建实例级角色,因此仅在共享实例内增加一个空数据库不足以隔离这些检查。不得指向共享开发、PR 预览或生产库。验收运行真实迁移,检查模型漂移,通过真实 ORM / PostgreSQL 和本地 Moto S3 服务验证发布、重试、并发冲突、失败回滚、私有分页、文档条件替换与快照域隔离、blocked 读取、GET / HEAD 和 ETag 重验证。迁移使用 owner,业务验收使用 `registry_app`,并验证创建表、修改业务表、写迁移记录和创建角色均被拒绝。D1 导入验收使用临时 SQLite 快照,比较所有逻辑字段的内容摘要。测试仅在空库插入测试记录,并在退出时清理;失败可能保留 schema 和迁移记录,目标库仍须属于一次性验证生命周期。 +CI 创建 PostgreSQL 17 service。本地每次运行都使用新的独立 PostgreSQL 实例或 Neon 测试分支,数据库编码使用 UTF-8。授权迁移会创建实例级角色,因此共享实例里的空数据库也无法隔离这些检查。验收先只读检查公开 schema 和 `registry_app` 角色,然后用含历史发行和文档数据的夹具回放升级。事务、并发上传冲突、Simple 索引、目录回跳、文档生命周期和 HTTP 缓存行为经过真实 ORM、PostgreSQL 和本地 Moto S3。迁移使用 owner,业务验收使用 `registry_app`,并验证创建表、修改业务表、写迁移记录和创建角色均被拒绝。D1 导入验收使用临时 SQLite 快照,比较所有逻辑字段的内容摘要。运行后会保留迁移和角色,供 CI 随后的服务镜像验收使用。再次运行须重建实例。 `pnpm registry:check` 单独执行上述验收,仍需要同一个测试变量。CI 另外拒绝修改或删除已在 base 中存在的迁移,并构建完整服务镜像。测试数据不会写入共享预览。 @@ -35,7 +37,7 @@ Registry 通过不可变 Git commit 安装 `InKCre/ui` 的 `@inkcre/ui-web` 公 Toolkit、Core Runtime 与 Web Runtime 保持各自的版本和发布机制。`pnpm build` 构建这些独立产物;Registry 的容器部署不会发布它们,也不会引入单独的前端部署流程。 Web Runtime 的 Core SDK 开发依赖使用官方预构建 GitHub Release tgz,完整性记录在 pnpm 锁文件中;构建无需跨仓检出源码或运行 SDK 准备脚本。 -`pnpm packages:check` 在构建后创建独立虚拟环境,通过 wheel metadata 解析安装 Registry 与本次 Toolkit 候选,再执行 `pip check` 和服务 import;它不加载 workspace 源码,防止可编辑安装掩盖错误依赖边界。该检查需要包索引访问并随 `pnpm check` 运行。Registry 的文档 API 要求 Toolkit `>=0.5,<0.6`。Python 改动在所属 project 的 `.changes/` 记录 Towncrier fragment;Web Runtime 使用 `.changeset/`。合并普通改动后,Version PR 才准备版本与 changelog,正式产物只从准备完成的 `main` 发布。 +`pnpm packages:check` 在构建后创建独立虚拟环境,安装候选 Registry、Toolkit 和 Python Runtime wheel,再执行 `pip check` 和服务 import。验收用安装后的 Toolkit CLI 生成文档和静态目录,Python Runtime 从该目录的本地 HTTP Simple 索引通过标准 pip 下载并安装精确发行。该检查需要包索引访问并随 `pnpm check` 运行。Registry 的文档 API 要求 Toolkit `>=0.5,<0.6`。Python 改动在所属 project 的 `.changes/` 记录 Towncrier fragment;Web Runtime 使用 `.changeset/`。合并普通改动后,Version PR 才准备版本与 changelog,正式产物只从准备完成的 `main` 发布。 本次独立原生发行与 Peer 参与模型需要先生成候选 SDK 版本才能跨仓验证:Registry 0.3、Toolkit 0.5、Python Runtime 0.2 由既有 `scripts/release.py prepare` 生成,Web Runtime 0.4 由 Changesets 生成,相关 intents 已消费,后续不能再次升版。PR 58 使用维护者授予的 `coordinated-sdk-version-preparation` label 声明同一 PR 内包含功能与机械版本准备。CI 监听 label 添加/移除并从 PR metadata 决定是否传递 `--allow-feature-version-preparation`;日志显示该用途。这个开关只解除行为文件分类限制,仍要求版本/changelog 一致、版本前进、对应 fragments 已消费及全部质量检查。无 label 默认保持原有严格规则。本地完整验收使用 `BASE_REVISION= RELEASE_CHECK_ARGS=--allow-feature-version-preparation pnpm check`。 diff --git a/runtimes/web/check-boundaries.mjs b/runtimes/web/check-boundaries.mjs index 74f983e..376cfe8 100644 --- a/runtimes/web/check-boundaries.mjs +++ b/runtimes/web/check-boundaries.mjs @@ -196,11 +196,9 @@ try { ['2.0.0-beta.1', '1.10.0', '1.2.0'], ) assert.equal(preferredPublishedRelease(catalogReleases).version, '1.10.0') - assert.equal((await releases.getRelease('inkcre/catalog', '1.10.0', true)).version, '1.10.0') - assert.equal( - (await releases.get('inkcre/catalog', '1.10.0', true)).distribution, - 'module_federation', - ) + const exact = await releases.get('inkcre/catalog', '1.10.0', true) + assert.equal(exact.version, '1.10.0') + assert.equal(exact.module_federation.manifest_url, `${origin}/mf-manifest.json`) const originalGet = ExtensionParticipationModel.get const selection = { name: 'inkcre/catalog', diff --git a/scripts/check_documentation.py b/scripts/check_documentation.py index 92cf61b..9c3c052 100644 --- a/scripts/check_documentation.py +++ b/scripts/check_documentation.py @@ -29,14 +29,11 @@ def check_content_sites() -> None: """Configuration must keep each snapshot on its own valid content origin.""" for management, content, accepted in ( - ("https://registry.example.com", "https://{snapshot}.docs.example.com", True), ("https://registry.example.co.uk", "https://{snapshot}.docs.example.co.uk", True), ("https://registry.example.com", "https://{snapshot}.exampleusercontent.net", True), ("https://registry.team.github.io", "https://{snapshot}.docs.team.github.io", True), - ("https://registry.team.github.io", "https://{snapshot}.other.github.io", True), ("https://registry.example.com", "https://registry-docs-{snapshot}.example.com", True), ("https://registry.example.com", "https://docs.registry-{snapshot}.example.com", False), - ("http://localhost", "http://{snapshot}.docs.localhost", True), ("https://registry.example.com", "http://{snapshot}.docs.localhost", False), ): with patch.dict( @@ -141,7 +138,6 @@ async def upload(payload, content=zipped, expected=200, headers=None, scope="glo first_response = await upload(first) assert "etag" not in first_response.headers first_record = first_response.json() - assert (await upload(first)).json() == first_record assert (await request("GET", private, headers=authorization)).json()["sets"][0][ "snapshot_id" ] == first["snapshot_id"] diff --git a/scripts/check_installed_runtime.py b/scripts/check_installed_runtime.py new file mode 100644 index 0000000..cb15d1e --- /dev/null +++ b/scripts/check_installed_runtime.py @@ -0,0 +1,80 @@ +"""Run inside the isolated wheel environment against the Toolkit's HTTP preview output.""" + +import asyncio +import json +import sys +import tempfile +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock +from urllib.request import urlopen + +from inkcre_extension_runtime_core_py import ( + ExtensionEnvironmentApplicationRequiredError, + ExtensionManager, + ExtensionRegistryError, +) +from inkcre_extension_runtime_core_py.distribution import ( + AcquiredDistribution, + PipDistributionConsumer, +) +from inkcre_extension_runtime_core_py.release import ( + RegistryReleaseClient, + require_python_association, +) + + +def main(origin: str) -> None: + def read(path: str) -> bytes: + with urlopen(origin + path, timeout=10) as response: + return response.read() + + assert json.loads(read("/v2/extensions")) == [ + {"name": "check/catalog", "nickname": "Catalog check"} + ] + detail = json.loads(read("/v2/extensions/check/catalog/distributions/module_federation")) + remote = detail["releases"][0] + assert remote["name"] == "check/catalog" and remote["version"] == "1.10.0" + manifest = json.loads(read(remote["module_federation"]["manifest_url"])) + prefix = "/extensions/check/catalog/1.10.0/module-federation/" + assert manifest["metaData"]["publicPath"] == origin + prefix + assert read(prefix + "remoteEntry.js") == b"export const check = true;" + + name, version, host = "check/catalog", "1.2.3", "1.0.0" + catalog = RegistryReleaseClient(origin) + try: + catalog.get(name, "1.10.0") + except ExtensionRegistryError as error: + assert "different exact Release" in str(error) + else: + raise AssertionError("Python Runtime accepted a Release with a different coordinate") + release = catalog.get(name, version) + association = require_python_association(release, host) + selection = SimpleNamespace(name=name, distribution="python", version=version, enabled=False) + store = Mock() + store.get_participation.return_value = selection + manager = ExtensionManager( + store, {name: selection}, peer_id="check", registry_origin=origin, host_version=host + ) + + consumer = PipDistributionConsumer(origin) + with tempfile.TemporaryDirectory(prefix="extension-download-") as directory: + wheel = consumer.download(release, association, host, Path(directory)) + try: + asyncio.run(manager.enable(name)) + except ExtensionEnvironmentApplicationRequiredError: + pass + else: + raise AssertionError( + "Downloading a wheel must leave the running Peer unable to enable it" + ) + store.set_participation_enabled.assert_not_called() + assert AcquiredDistribution.discover(name, version, host) is None + + installed = consumer.apply(wheel, release, association, host) + assert installed.entry_point.load().marker == "preview wheel" + print("Installed Python Runtime applied the exact wheel from the preview Simple index.") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/scripts/check_packages.py b/scripts/check_packages.py index 31d1799..c0bdb20 100644 --- a/scripts/check_packages.py +++ b/scripts/check_packages.py @@ -1,4 +1,4 @@ -"""Check Runtime native boundaries and install built Registry/Toolkit wheels in isolation.""" +"""Qualify the shipped wheels and package delivery boundaries.""" from __future__ import annotations @@ -14,116 +14,18 @@ import tomllib import venv import zipfile +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path -from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock, patch -from urllib.parse import quote +from threading import Thread +from unittest.mock import patch -from inkcre_extension_toolkit.preview import build_preview_registry from packaging.requirements import Requirement +from wheel.wheelfile import WheelFile ROOT = Path(__file__).resolve().parents[1] -def check_web_app_handoff() -> None: - """Exercise the HTTP naming boundary with a controlled repository, without persistence.""" - from fastapi.testclient import TestClient - - from inkcre_extension_registry.contracts.models import ( - ExtensionSummary, - ModuleFederationDistribution, - NativeExtensionRecord, - NativeReleaseRecord, - ) - from inkcre_extension_registry.service.app import create_app - - release = NativeReleaseRecord( - name="check/example", - nickname="Example", - version="1.0.0", - state="published", - distribution="module_federation", - module_federation=ModuleFederationDistribution( - manifest_url="https://registry.invalid/mf-manifest.json", - host_sdk="@inkcre/core", - host_sdk_version=">=0.4.2 <0.5.0", - ), - ) - app = create_app() - app.state.repository = SimpleNamespace( - list_native_extensions=AsyncMock( - return_value=[ExtensionSummary(name=release.name, nickname=release.nickname)] - ), - get_native_extension=AsyncMock( - return_value=NativeExtensionRecord( - name=release.name, nickname=release.nickname, releases=(release,) - ) - ), - ) - app.state.settings = SimpleNamespace(documentation_origin_template=None) - # Deliberately omit lifespan: these routes consume only the controlled repository above. - browser = TestClient(app) - try: - for path in ("/", "/explore/check/example"): - for query, expected_origin in ( - ({"app_origin": "https://app.example"}, "https://app.example"), - ({"client_origin": "https://app.example/"}, "https://app.example"), - ( - {"app_origin": "https://app.example", "client_origin": "https://app.example/"}, - "https://app.example", - ), - ( - { - "app_origin": "https://APP.example:443", - "client_origin": "https://app.example/", - }, - "https://app.example", - ), - ( - {"app_origin": "http://LOCALHOST:80", "client_origin": "http://localhost/"}, - "http://localhost", - ), - ( - {"app_origin": "https://[::1]:443", "client_origin": "https://[::1]/"}, - "https://[::1]", - ), - ({"app_origin": "http://[::1]:5173"}, "http://[::1]:5173"), - ): - response = browser.get(path, params=query) - assert response.status_code == 200, response.text - assert "client_origin" not in response.text - assert f"app_origin={quote(expected_origin)}" in response.text - if path != "/": - assert ( - f'href="{expected_origin}/extensions?install=check%2Fexample' - in response.text - ) - assert browser.get(path).status_code == 200 - assert ( - browser.get( - path, - params={ - "app_origin": "https://one.example", - "client_origin": "https://two.example", - }, - ).status_code - == 400 - ) - for parameter in ("app_origin", "client_origin"): - for invalid in ( - "", - "http://public.example", - "https://app.example/path", - "javascript:bad", - ): - assert browser.get(path, params={parameter: invalid}).status_code == 400 - assert browser.get(path, params={parameter: "x" * 513}).status_code == 422 - assert "https://app.inkcre.dev/extensions?" in browser.get("/explore/check/example").text - finally: - browser.close() - print("Web App handoff preserves legacy origins, canonical links and conflict rejection.") - - def check_production_delivery_boundary() -> None: from contextlib import redirect_stdout @@ -197,7 +99,7 @@ def client_factory(*args, provider=provider, **kwargs): "AWS_ACCESS_KEY_ID": "synthetic-key", "AWS_SECRET_ACCESS_KEY": "synthetic-secret", } - for quantity, state, partial, failure in [ + for quantity, state, partial_listing, failure in [ (1, None, False, None), (0, "up", False, None), (0, "starting", False, None), @@ -214,14 +116,18 @@ def client_factory(*args, provider=provider, **kwargs): output = io.StringIO() def provider( - request: httpx.Request, events=events, quantity=quantity, state=state, partial=partial + request: httpx.Request, + events=events, + quantity=quantity, + state=state, + partial_listing=partial_listing, ) -> httpx.Response: events.append((request.method, request.url.path)) if request.url.path.endswith("/formation/web"): body = {"type": "web", "quantity": quantity} elif request.url.path.endswith("/dynos"): body = [] if state is None else [{"type": "web", "state": state}] - return httpx.Response(206 if partial else 200, json=body) + return httpx.Response(206 if partial_listing else 200, json=body) else: body = {"stack": {"name": "container"}} return httpx.Response(200, json=body) @@ -242,7 +148,7 @@ def smoke(*args, events=events, failure=failure): if failure == "smoke": raise RuntimeError("synthetic smoke failure") - refused = quantity != 0 or state in {"up", "starting", "idle", "unknown"} or partial + refused = quantity != 0 or state in {"up", "starting", "idle", "unknown"} or partial_listing with ( httpx.Client( base_url="https://api.heroku.com/", transport=httpx.MockTransport(provider) @@ -284,116 +190,7 @@ def smoke(*args, events=events, failure=failure): print("Production stopped-web gate and ordered failure boundaries passed.") -def check_native_runtime_boundary() -> None: - import asyncio - - from inkcre_extension_runtime_core_py import ExtensionEnvironmentApplicationRequiredError - from inkcre_extension_runtime_core_py.distribution import ( - AcquiredDistribution, - PipDistributionConsumer, - ) - from inkcre_extension_runtime_core_py.errors import ExtensionRegistryError - from inkcre_extension_runtime_core_py.manager import ExtensionManager - from inkcre_extension_runtime_core_py.release import RegistryReleaseClient - - body = { - "name": "check/extension", - "nickname": "Check", - "version": "1.2.3", - "state": "published", - "distribution": "python", - "module_federation": None, - "python": { - "project": "check-extension", - "host_sdk": "core-py", - "host_sdk_version": ">=0.1.0", - "simple_url": "/simple/check-extension/", - "entry_point": { - "group": "inkcre.core.extensions", - "name": "extension", - "object": "extensions.check:Extension", - }, - }, - } - response = Mock() - response.json.return_value = body - with patch("requests.get", return_value=response) as get: - release = RegistryReleaseClient("https://registry.invalid").get("check/extension", "1.2.3") - assert release.version == "1.2.3" - assert get.call_args.args[0].endswith( - "/v2/extensions/check/extension/distributions/python/releases/1.2.3" - ) - assert release.python is not None - commands: list[list[str]] = [] - installed_record = { - "schema_version": 1, - "name": release.name, - "version": release.version, - "host_sdk": {"name": "core-py", "version": ">=0.1.0"}, - "python": { - "project": release.python.project, - "project_version": "1.2.3", - "entry_point": release.python.entry_point.model_dump(mode="json"), - }, - } - - def runner(arguments: list[str]) -> subprocess.CompletedProcess[str]: - commands.append(arguments) - if arguments[0] == "download": - destination = Path(arguments[arguments.index("--dest") + 1]) - with zipfile.ZipFile( - destination / "check_extension-1.2.3-py3-none-any.whl", "w" - ) as wheel: - wheel.writestr( - "check_extension-1.2.3.dist-info/inkcre-extension.json", - json.dumps(installed_record), - ) - return subprocess.CompletedProcess(arguments, 0, "", "") - - consumer = PipDistributionConsumer("https://registry.invalid", runner=runner) - with tempfile.TemporaryDirectory(prefix="runtime-wheel-check-") as directory: - wheel_path = consumer.download(release, release.python, "0.1.0", Path(directory)) - assert [command[0] for command in commands] == ["download"] - acquired = Mock() - with patch.object(AcquiredDistribution, "discover", return_value=acquired): - assert consumer.apply(wheel_path, release, release.python, "0.1.0") is acquired - assert [command[0] for command in commands] == ["download", "install"] - body["distribution"] = "module_federation" - try: - RegistryReleaseClient("https://registry.invalid").get("check/extension", "1.2.3") - except ExtensionRegistryError: - pass - else: - raise AssertionError("Python reader accepted a different native coordinate") - - store = Mock() - store.get_participation.return_value = SimpleNamespace( - name="check/extension", distribution="python", version="1.2.3", enabled=False - ) - manager = ExtensionManager( - store, - Mock(), - peer_id="peer-check", - registry_origin="https://registry.invalid", - host_version="0.1.0", - ) - with ( - patch.object(AcquiredDistribution, "discover", return_value=None), - patch( - "subprocess.run", - side_effect=AssertionError("running Peer attempted environment mutation"), - ), - ): - try: - asyncio.run(manager.enable("check/extension")) - except ExtensionEnvironmentApplicationRequiredError: - pass - else: - raise AssertionError("missing wheel must require stopped-Peer environment application") - store.set_participation_enabled.assert_not_called() - - -def check_preview_catalog() -> None: +def check_preview_catalog(python: Path) -> None: with tempfile.TemporaryDirectory(prefix="registry-preview-check-") as temporary: root = Path(temporary) artifact = root / "remote" @@ -425,6 +222,60 @@ def check_preview_catalog() -> None: } ) ) + python_producer = root / "pyproject.toml" + python_producer.write_text( + """[project] +name = "inkcre-acceptance-preview" +version = "1.2.3" + +[project.entry-points."inkcre.core.extensions"] +example = "inkcre_acceptance_preview:Extension" + +[tool.inkcre-extension] +name = "check/catalog" +nickname = "Catalog check" +host-sdk = "core-py" +host-sdk-version = "^1.0.0" +""" + ) + wheel = root / "inkcre_acceptance_preview-1.2.3-py3-none-any.whl" + wheel_info = "inkcre_acceptance_preview-1.2.3.dist-info/" + with WheelFile(wheel, "w") as package: + package.writestr( + "inkcre_acceptance_preview.py", 'class Extension:\n marker = "preview wheel"\n' + ) + package.writestr( + wheel_info + "METADATA", + "Metadata-Version: 2.3\nName: inkcre-acceptance-preview\nVersion: 1.2.3\n\n", + ) + package.writestr( + wheel_info + "WHEEL", + "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n", + ) + package.writestr( + wheel_info + "entry_points.txt", + "[inkcre.core.extensions]\nexample = inkcre_acceptance_preview:Extension\n", + ) + package.writestr( + wheel_info + "inkcre-extension.json", + json.dumps( + { + "schema_version": 1, + "name": "check/catalog", + "version": "1.2.3", + "host_sdk": {"name": "core-py", "version": "^1.0.0"}, + "python": { + "project": "inkcre-acceptance-preview", + "project_version": "1.2.3", + "entry_point": { + "group": "inkcre.core.extensions", + "name": "example", + "object": "inkcre_acceptance_preview:Extension", + }, + }, + } + ), + ) inventory = root / "inventory.json" inventory.write_text( json.dumps( @@ -435,28 +286,69 @@ def check_preview_catalog() -> None: "kind": "module_federation", "producer": producer.name, "artifact": artifact.name, - } + }, + { + "kind": "python", + "producer": python_producer.name, + "artifact": wheel.name, + }, ], } ) ) output = root / "output" - build_preview_registry(inventory, "https://registry.example.test", output) - assert json.loads((output / "v2/extensions.json").read_text()) == [ - {"name": "check/catalog", "nickname": "Catalog check"} - ] - detail = json.loads( - ( - output / "v2/extensions/check/catalog/distributions/module_federation.json" - ).read_text() - ) - assert detail["name"] == "check/catalog" and detail["releases"][0]["version"] == "1.10.0" - redirects = (output / "_redirects").read_text() - assert "/v2/extensions /v2/extensions.json 200" in redirects - assert ( - "/v2/extensions/check/catalog/distributions/module_federation " - "/v2/extensions/check/catalog/distributions/module_federation.json 200" in redirects - ) + rewrites: dict[str, str] = {} + + class PreviewHandler(SimpleHTTPRequestHandler): + def do_GET(self) -> None: + self.path = rewrites.get(self.path, self.path) + super().do_GET() + + def log_message(self, format, *args) -> None: + pass + + with ThreadingHTTPServer( + ("127.0.0.1", 0), partial(PreviewHandler, directory=output) + ) as server: + origin = f"http://127.0.0.1:{server.server_port}" + subprocess.run( + [ + str(python), + "-I", + str(python.parent / "inkcre-ext"), + "preview", + "build", + "--inventory", + str(inventory), + "--public-origin", + origin, + "--output", + str(output), + ], + cwd=root, + check=True, + ) + for line in (output / "_redirects").read_text().splitlines(): + route, target, status = line.split() + assert status == "200", line + rewrites[route] = target + + # A misrouted Python request can receive the Web release at the same version. + distribution = "/v2/extensions/check/catalog/distributions/" + web = distribution + "module_federation/releases/1.10.0" + rewrites[distribution + "python/releases/1.10.0"] = rewrites[web] + thread = Thread(target=server.serve_forever) + thread.start() + try: + subprocess.run( + [str(python), "-I", str(ROOT / "scripts/check_installed_runtime.py"), origin], + cwd=root, + check=True, + timeout=60, + ) + finally: + server.shutdown() + thread.join() def check_native_toolkit_cli(python: Path) -> None: @@ -495,23 +387,7 @@ def check_native_toolkit_cli(python: Path) -> None: ) candidate = json.loads((output / "candidate.json").read_text()) assert candidate["distribution"] == "python" and candidate["scope"] == "global" - subprocess.run( - [ - str(python), - "-I", - "-c", - "from inkcre_extension_toolkit.client import RegistryClient; " - "assert all(not hasattr(RegistryClient, method) for method in " - "('prepare','upload_module_federation','publish','yank','unyank')); " - "assert all(hasattr(RegistryClient, method) for method in " - "('prepare_native','publish_native','get_native_release','get_release','get_documentation'))", - ], - cwd=fixture, - check=True, - ) - print( - "Installed Toolkit CLI persists native documentation identity; retired writes are absent." - ) + print("Installed Toolkit CLI persists native documentation identity.") def check_coordinated_version_preparation() -> None: @@ -579,7 +455,6 @@ def check(*arguments): flag = "--allow-feature-version-preparation" admitted = check(flag) assert admitted.returncode == 0, admitted.stderr - assert "This does not authorize publication" in admitted.stdout residual = fixture / ".changes/+residual.fixed.md" residual.write_text("An unconsumed release intent.\n") rejected = check(flag) @@ -620,13 +495,10 @@ def check(*arguments): def main() -> None: - check_web_app_handoff() check_production_delivery_boundary() check_coordinated_version_preparation() - check_native_runtime_boundary() - check_preview_catalog() wheels = [] - for directory in (ROOT, ROOT / "toolkit"): + for directory in (ROOT, ROOT / "toolkit", ROOT / "runtimes/core-py"): project = tomllib.loads((directory / "pyproject.toml").read_text())["project"] wheels.append( ROOT @@ -670,9 +542,7 @@ def main() -> None: str(python), "-I", "-c", - "from inkcre_extension_registry.service.app import create_app; " - "from inkcre_extension_toolkit.documentation import inspect_documentation; " - "assert create_app().openapi()['paths']['/v1/documentation-hosting']", + "from inkcre_extension_registry.service.app import create_app; create_app()", ], cwd=environment, check=True, @@ -692,7 +562,8 @@ def main() -> None: check=True, ) check_native_toolkit_cli(python) - print("Registry and Toolkit wheel metadata, isolated installation and service import passed.") + check_preview_catalog(python) + print("Registry, Toolkit and Python Runtime isolated wheel installation and acceptance passed.") if __name__ == "__main__": diff --git a/scripts/check_registry.py b/scripts/check_registry.py index aaad5ac..7c012ed 100644 --- a/scripts/check_registry.py +++ b/scripts/check_registry.py @@ -8,6 +8,7 @@ import asyncio import hashlib +import html import io import json import logging @@ -15,6 +16,7 @@ import secrets import zipfile from unittest.mock import patch +from urllib.parse import quote import httpx import psycopg @@ -31,7 +33,6 @@ from inkcre_extension_registry.service import database as db from inkcre_extension_registry.service.app import create_app -from inkcre_extension_registry.service.repository import RegistryRepository from inkcre_extension_registry.service.settings import database_config @@ -141,19 +142,19 @@ async def request(method: str, path: str, expected: int = 200, *, private=False, assert mf_record["distribution"] == "module_federation" and mf_record["python"] is None await request("GET", python_path, 404) metadata = "Metadata-Version: 2.3\nName: check-extension\nVersion: 1.0.0\n\n" - wheel = archive( - { - "check.py": "class Extension: pass\n", - "check_extension-1.0.0.dist-info/METADATA": metadata, - "check_extension-1.0.0.dist-info/entry_points.txt": ( - "[inkcre.core.extensions]\ncheck = check:Extension\n" - ), - "check_extension-1.0.0.dist-info/WHEEL": ( - "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n" - ), - "check_extension-1.0.0.dist-info/RECORD": "", - } - ) + metadata_path = "check_extension-1.0.0.dist-info/METADATA" + wheel_files = { + "check.py": "class Extension: pass\n", + metadata_path: metadata, + "check_extension-1.0.0.dist-info/entry_points.txt": ( + "[inkcre.core.extensions]\ncheck = check:Extension\n" + ), + "check_extension-1.0.0.dist-info/WHEEL": ( + "Wheel-Version: 1.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n" + ), + "check_extension-1.0.0.dist-info/RECORD": "", + } + wheel = archive(wheel_files) wheel_name = "check_extension-1.0.0-py3-none-any.whl" upload = { ":action": "file_upload", @@ -182,25 +183,30 @@ async def request(method: str, path: str, expected: int = 200, *, private=False, await artifacts.put( file.metadata_r2_key, metadata.encode(), content_type="application/octet-stream" ) - original_check = RegistryRepository._release_objects_available + head = artifacts.head + competing_name = "check_extension-1.0.0-1-py3-none-any.whl" + competing_wheel = archive( + {**wheel_files, metadata_path: metadata.rstrip() + "\nSummary: Second build\n\n"} + ) - async def concurrent_file_upload(repository, row): - ready = await original_check(repository, row) - fields = await db.PythonFile.filter(id=file.id).values() - fields[0].pop("id") - fields[0]["filename"] = "check_extension-1.0.0-1-py3-none-any.whl" - fields[0]["r2_key"] += ".concurrent" - fields[0]["metadata_r2_key"] += ".concurrent" - await artifacts.put(fields[0]["r2_key"], wheel, content_type="application/octet-stream") - await artifacts.put( - fields[0]["metadata_r2_key"], metadata.encode(), content_type="application/octet-stream" - ) - await db.PythonFile.create(**fields[0]) - return ready + async def interleave_upload(key): + stored = await head(key) + if key == file.r2_key: + await request( + "POST", + "/legacy/", + private=True, + data={**upload, "sha256_digest": hashlib.sha256(competing_wheel).hexdigest()}, + files={"content": (competing_name, competing_wheel)}, + ) + return stored - with patch.object(RegistryRepository, "_release_objects_available", concurrent_file_upload): - await request("POST", python_path + "/publish", 409, private=True) - assert (await db.NativeRelease.get(distribution="python")).state == "preparing" + # The candidate is read before object I/O. Commit a second upload before that I/O returns. + with patch.object(artifacts, "head", interleave_upload): + async with asyncio.timeout(10): + conflict = await request("POST", python_path + "/publish", 409, private=True) + assert "Distributions changed during publication" in conflict.text + await request("GET", python_path, 404) py_record = (await request("POST", python_path + "/publish", private=True)).json() assert py_record["distribution"] == "python" and py_record["module_federation"] is None await request("POST", python_path + "/publish", private=True) @@ -209,12 +215,15 @@ async def concurrent_file_upload(repository, row): assert [r["version"] for r in py_versions] == ["1.0.0"] and [ r["version"] for r in mf_versions ] == ["2.0.0"] - await request("GET", "/explore/check/extension?distribution=python&version=1.0.0") - await request("GET", "/explore/check/extension?distribution=module_federation&version=2.0.0") + await check_catalog_handoff(request) assert (await request("GET", "/v1/extensions")).json() == [] await request("GET", "/v1/extensions/check/extension/releases/1.0.0", 404) package = f"/packages/check-extension/1.0.0/{wheel_name}" remote = "/extensions/check/extension/2.0.0/module-federation/remoteEntry.js" + assert 'href="/simple/check-extension/"' in (await request("GET", "/simple/")).text + index = (await request("GET", "/simple/check-extension/")).text + assert f'href="{package}#sha256={upload["sha256_digest"]}"' in index + assert f'data-core-metadata="sha256={hashlib.sha256(metadata.encode()).hexdigest()}"' in index assert (await request("GET", package)).content == wheel assert (await request("GET", package + ".metadata")).text == metadata assert (await request("GET", remote)).content == b"export const check = true;" @@ -255,6 +264,48 @@ async def concurrent_file_upload(repository, row): await request("GET", "/v2/publisher", 401, private=True) +async def check_catalog_handoff(request) -> None: + detail = "/explore/check/extension" + origin = "https://app.example" + canonical = f"app_origin={quote(origin)}" + catalog = await request("GET", "/", params={"client_origin": origin + "/"}) + page = await request("GET", f"{detail}?{canonical}") + assert f'href="{detail}?{canonical}"' in catalog.text + install = "/extensions?install=check%2Fextension&distribution=module_federation&version=2.0.0" + assert f'href="{origin}{install}"' in html.unescape(page.text) + for query, expected_origin in ( + ({"client_origin": origin + "/"}, origin), + ({"app_origin": "https://APP.example:443", "client_origin": origin}, origin), + ({"app_origin": "http://[::1]:5173"}, "http://[::1]:5173"), + ({}, "https://app.inkcre.dev"), + ): + page = await request("GET", detail, params=query) + assert f'href="{expected_origin}{install}"' in html.unescape(page.text) + python = await request("GET", detail, params={"distribution": "python", "version": "1.0.0"}) + assert 'href="/simple/check-extension/"' in python.text + for path in ("/", detail): + await request( + "GET", + path, + 400, + params={"app_origin": origin, "client_origin": "https://other.example"}, + ) + await request("GET", detail, 400, params={"app_origin": "http://app.example"}) + + +def require_fresh_database(url: str) -> None: + with psycopg.connect(url, autocommit=True, connect_timeout=10) as connection: + occupied = connection.execute( + """SELECT EXISTS (SELECT FROM pg_catalog.pg_tables WHERE schemaname = 'public') + OR EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'registry_app')""" + ).fetchone() + if occupied and occupied[0]: + raise SystemExit( + "Registry acceptance needs a fresh disposable PostgreSQL instance. " + "The target already contains public tables or the registry_app role." + ) + + def check_runtime_permissions(url: str) -> None: with psycopg.connect(url, autocommit=True) as connection: for statement in ( @@ -385,7 +436,12 @@ async def check_native_upgrade(executor: MigrationExecutor) -> None: async def main() -> None: - owner_url = os.environ["REGISTRY_TEST_DATABASE_URL"] + owner_url = os.environ.get("REGISTRY_TEST_DATABASE_URL") + if not owner_url: + raise SystemExit( + "Set REGISTRY_TEST_DATABASE_URL to a fresh disposable PostgreSQL instance." + ) + await asyncio.to_thread(require_fresh_database, owner_url) config = database_config(owner_url) async with TortoiseContext() as context: await context.init(config=config) @@ -395,10 +451,7 @@ async def main() -> None: ) executor = MigrationExecutor(Tortoise.get_connection("default"), config["apps"]) await executor.loader.build_graph() - if not await executor.recorder.applied_migrations(): - await check_native_upgrade(executor) - else: - await executor.migrate(direction="forward") + await check_native_upgrade(executor) assert not await executor.plan(), "Migration head was not reached" assert not await db.Namespace.exists(), "Checks require an empty disposable database" url = await asyncio.to_thread(configure_runtime_login, owner_url, secrets.token_urlsafe(32))