diff --git a/.changes/retire-d1-import.changed.md b/.changes/retire-d1-import.changed.md new file mode 100644 index 0000000..858019b --- /dev/null +++ b/.changes/retire-d1-import.changed.md @@ -0,0 +1 @@ +Registry 日常验收和安装包移除一次性 D1 导入器。旧 D1 快照可按生产手册从固定历史版本回放。 diff --git a/AGENTS.md b/AGENTS.md index 5346a11..400cce6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ The Registry owns releases. The info-base records deployment Extension identity, - `src/inkcre_extension_registry/migrations/`: active PostgreSQL migrations - `toolkit/`: independently released developer and delivery tooling (Python, `inkcre_extension_toolkit`) - `contracts/`: generated schemas and OpenAPI; never edit by hand -- `migrations/`: legacy D1 schema retained for import and recovery +- `migrations/`: historical D1 source schema for pinned recovery replay - `scripts/`: contract generation, verification, and release tooling - `runtimes/`: runtime topology for local and preview - `docs/30-unit-tdd/`: internal design diff --git a/docs/30-unit-tdd/registry-control-plane.md b/docs/30-unit-tdd/registry-control-plane.md index 898f6c9..0ad3d65 100644 --- a/docs/30-unit-tdd/registry-control-plane.md +++ b/docs/30-unit-tdd/registry-control-plane.md @@ -68,7 +68,7 @@ and `blocked` denies discovery, stable entries, and every historical snapshot be R2 的网络访问不持有数据库事务锁。boto3 的同步调用在线程中执行;上传先写内容寻址的 staging 对象,再在 PostgreSQL 事务中增加可见关联。发布前检查关联对象存在,文件大小一致。失败可能留下不可达的 staging 对象,它们不是公开状态的来源。每次文件读取先检查 release 可读性,再通过 S3 流式返回;HEAD 只读取对象元数据。响应使用 `Cache-Control: public, no-cache` 和内容 SHA-256 ETag;条件 GET / HEAD 在 release 可读、对象存在之后才能返回 304。缓存必须逐次重验证,blocked 的 451 响应使用 `no-store`。已经被客户端下载的内容无法通过服务端状态变化收回。 -应用启动只初始化连接池,不建表、不运行迁移、不创建凭据或示例数据。交付在启动新版本前运行包内 Tortoise 迁移,并仅允许向前执行。数据迁移工具只在旧 SQLite 快照读取边界使用 SQL,PostgreSQL 业务读写与发布凭据维护使用 ORM。角色与 GRANT 是 PostgreSQL 原生授权 DDL,由追加迁移维护;登录密码由可信交付端设置。运行角色 `registry_app` 仅获得明确列出的业务表的 SELECT / INSERT / UPDATE / DELETE、对应序列的 USAGE 和 schema 的 USAGE,不能修改 schema、角色或迁移记录。后续新增表须在同一迁移显式授予所需权限,不自动授权全部未来表。旧 D1 历史保留用于导入验收,迁移工具不自动访问生产 D1。 +应用启动只初始化连接池,不建表、不运行迁移、不创建凭据或示例数据。交付在启动新版本前运行包内 Tortoise 迁移,并仅允许向前执行。PostgreSQL 业务读写与发布凭据维护使用 ORM。角色与 GRANT 是 PostgreSQL 原生授权 DDL,由追加迁移维护;登录密码由可信交付端设置。运行角色 `registry_app` 仅获得明确列出的业务表的 SELECT / INSERT / UPDATE / DELETE、对应序列的 USAGE 和 schema 的 USAGE,不能修改 schema、角色或迁移记录。后续新增表须在同一迁移显式授予所需权限,不自动授权全部未来表。旧 D1 恢复使用[固定版本的导入流程](../40-deployment/production-registry.md#历史-d1-导入回放)。 Publisher 持有 namespace 范围内的发布能力;原始 token 只用于请求认证和运维命令的标准输入,数据库保存 SHA-256。匿名读取只能看到公开或撤回的 release,blocked 状态拒绝描述和原始文件访问。预览服务只获得所属数据库分支和 R2 桶的凭据;云平台控制凭据只属于可信交付控制器。 @@ -78,4 +78,4 @@ Registry 验证文件结构与完整性,不证明发布者可信。Python 扩 发布检查只覆盖当前原生发行自己的全部字节:Python 至少一个 wheel 及其 metadata,MF 为 manifest 与全部资产。对象检查不持有数据库锁;提交前锁定原生发行并重新读取文件与 snapshot 身份,检查期间新增文件会导致 409,发布者可重试当前集合。 -`0005` 为历史每个关联生成独立原生坐标并重挂原有关联;保留文件主键、R2 key、时间、来源及原生元数据。历史 published/yanked 关联若没有 wheel 或 MF manifest,原生状态降为 preparing;blocked 保留。`0006` 为新文档增加 native owner,不修改已有快照、receipt、稳定 URL 或历史 owner。非空旧 schema 回放、D1 导入对照及真实 HTTP 检查共同验证此边界。部署只前进迁移,不把新的应用回退到只能解释统一发行的版本。 +`0005` 为历史每个关联生成独立原生坐标并重挂原有关联;保留文件主键、R2 key、时间、来源及原生元数据。历史 published/yanked 关联若没有 wheel 或 MF manifest,原生状态降为 preparing;blocked 保留。`0006` 为新文档增加 native owner,不修改已有快照、receipt、稳定 URL 或历史 owner。日常验收通过非空旧 schema 回放及真实 HTTP 检查验证此边界。部署只前进迁移,不把新的应用回退到只能解释统一发行的版本。 diff --git a/docs/40-deployment/local-development.md b/docs/40-deployment/local-development.md index ef505c1..e382598 100644 --- a/docs/40-deployment/local-development.md +++ b/docs/40-deployment/local-development.md @@ -27,7 +27,7 @@ pdm run python -m inkcre_extension_registry 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 测试分支。授权迁移会创建实例级角色,因此仅在共享实例内增加一个空数据库不足以隔离这些检查。不得指向共享开发、PR 预览或生产库。验收运行真实迁移,检查模型漂移,通过真实 ORM / PostgreSQL 和本地 Moto S3 服务验证发布、重试、并发冲突、失败回滚、私有分页、文档条件替换与快照域隔离、blocked 读取、GET / HEAD 和 ETag 重验证。迁移使用 owner,业务验收使用 `registry_app`,并验证创建表、修改业务表、写迁移记录和创建角色均被拒绝。测试仅在空库插入测试记录,并在退出时清理;失败可能保留 schema 和迁移记录,目标库仍须属于一次性验证生命周期。 `pnpm registry:check` 单独执行上述验收,仍需要同一个测试变量。CI 另外拒绝修改或删除已在 base 中存在的迁移,并构建完整服务镜像。测试数据不会写入共享预览。 diff --git a/docs/40-deployment/production-registry.md b/docs/40-deployment/production-registry.md index 3ee3b61..d20623a 100644 --- a/docs/40-deployment/production-registry.md +++ b/docs/40-deployment/production-registry.md @@ -27,7 +27,7 @@ Heroku 交付为 Uvicorn 设置 `FORWARDED_ALLOW_IPS=*`,由平台 HTTP 入口 首次部署因 GitHub production 环境的旧 `HEROKU_API_KEY` 失效,在读取 app 的 `stopped_web_check` 阶段返回 401,未进入数据库迁移。操作员确认 schema、旧 release、formation 和恢复材料未变后,将同名 secret 更新为同一现有 Heroku 主体的有效授权,再对同一精确来源重试成功;没有新建 token、增加权限或修改数据库/R2 凭据。这也是维护前只读凭据预检与即时阶段日志的必要性。 -以下 D1 导入、路由切换和恢复坐标记载的是 2026-09-13 的历史迁移。其旧入口只读可继续的做法,不适用于上述同库不兼容迁移。 +以下首次切换、故障恢复和旧资源坐标记载的是 2026-09-13 的历史迁移。其旧入口只读可继续的做法,不适用于上述同库不兼容迁移。 ## 生产资源与 TLS @@ -44,11 +44,26 @@ Heroku ACM 已为 `registry.inkcre.dev` 与 `*.inkcre.dev` 分别签发公开受 1. 明确来源 D1、目标 PostgreSQL、R2 桶、Heroku app、公开路由和获准变更窗口。先验证空库迁移、快照导入及整个发布流程;保存旧 Worker 版本与现有路由配置。 2. 暂停旧入口的发布写入并等待在途请求结束。本次使用 hostname 级临时 WAF 规则,拒绝 `registry.inkcre.dev` 的非 GET / HEAD / OPTIONS 请求,并实测规则生效;旧 Worker 的 workers.dev 和版本预览入口均关闭。停止 Web、Toolkit、CI publisher 等所有写入来源;只读分发可以继续。不要在旧入口仍接收写入时进行最终导入,也不要引入临时双写。 3. 使用 `pnpm dlx wrangler@4.120.0 d1 export --remote --output ` 保存最终快照。来源 ID 显式传入,不从已删除的 Worker 配置猜测。限制快照文件权限;它包含凭据哈希和私有元数据。用 SQLite 将这份受信任导出转换成临时 SQLite 文件,执行完整性与外键检查。原始 token 从不进入快照。 -4. 对空目标运行 `pnpm db:migrate`,然后运行 `pdm run python -m inkcre_extension_registry.import_d1 `。导入器拒绝非空目标,在同一事务中转换内部 ID 并核验每张表全部逻辑字段的规范化内容摘要;任何失败回滚全部导入。旧时间戳、空值、JSON、凭据哈希、release 状态及 R2 key 都参与比较。 +4. 对空目标执行[历史 D1 导入回放](#历史-d1-导入回放)。导入器拒绝非空目标,在同一事务中转换内部 ID 并核验每张表全部逻辑字段的规范化内容摘要;任何失败回滚全部导入。旧时间戳、空值、JSON、凭据哈希、release 状态及 R2 key 都参与比较。 5. 再运行同一命令并加 `--verify-only`。保存仅含行数和摘要的报告;抽查既有 wheel、Core Metadata、MF manifest / assets 的实际 R2 内容与公开身份。导入不移动、重写或公开 R2 对象。旧 `migrations/` 是来源 schema 历史,包内 Tortoise 迁移是新库 schema 历史。 6. 启动已验证镜像,先通过 app origin 验证只读目录、详情、私有认证和原生协议。预先完成 Heroku 域名及回源证书配置并校验证书与主机名,再移除 Worker Custom Domain、创建上述代理 CNAME。按 hostname 清除旧缓存,等待路由收敛,并验证缓存、ETag、GET / HEAD、Simple 内容协商及下载。再次导出旧 D1,确认隔离后摘要仍与导入来源相等,随后移除临时 WAF 写入暂停规则,恢复新服务的发布能力。 7. 保存最终来源快照、导入摘要、镜像 revision、数据库迁移位置及路由验收。旧 D1 / Worker 的删除须在约定保留窗口后另行执行,不能以 PR 合并代替资源删除授权。 +## 历史 D1 导入回放 + +从 [`2a03bbb05e02fb7e9841149aa5bcb88a12e94fe9`](https://github.com/InKCre/ext-reg/tree/2a03bbb05e02fb7e9841149aa5bcb88a12e94fe9) 单独检出历史 Registry。该提交保存 D1 来源 schema、导入器、验收和配套 PostgreSQL 迁移。使用 Python 3.13、`pdm==2.28.0`、`hishel==1.4.0` 和 `unearth==0.18.3` 安装该版本的锁定依赖。 + +将可信的历史快照转换为 SQLite 文件,先运行 `PRAGMA integrity_check` 和 `PRAGMA foreign_key_check`。通过 `MIGRATION_DATABASE_URL` 指定专用空 PostgreSQL 目标的 owner 连接。演练使用独立实例,因为迁移会创建实例级角色 `registry_app`。从历史 checkout 依次执行: + +```bash +pdm install --frozen-lockfile +pdm run tortoise -c inkcre_extension_registry.migration_config.TORTOISE_ORM upgrade +pdm run python -m inkcre_extension_registry.import_d1 /path/to/snapshot.sqlite +pdm run python -m inkcre_extension_registry.import_d1 /path/to/snapshot.sqlite --verify-only +``` + +两次命令的逐表行数和摘要应一致。先导入并核验固定版本的 schema,再按目标服务版本向前迁移。演练可在独立的一次性 PostgreSQL 实例运行历史 checkout 的 `pdm run python scripts/check_registry.py`,以 `REGISTRY_TEST_DATABASE_URL` 指定空库。该检查自建合成 D1 快照和本地 Moto S3。 + ## 故障恢复 切流前任何失败都维持旧入口的写入暂停,调查目标库和对象状态后重试;如果取消切换,可恢复旧入口写入。导入器不会清空已有目标,失败后只有在确认它是本次专属迁移目标时才能重建。 diff --git a/scripts/check_d1_import.py b/scripts/check_d1_import.py deleted file mode 100644 index 1ba7bbf..0000000 --- a/scripts/check_d1_import.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Verify the legacy schema conversion in the existing disposable database check.""" - -import copy -import sqlite3 -import tempfile -from pathlib import Path - -from tortoise.exceptions import IntegrityError - -from inkcre_extension_registry.import_d1 import ( - fingerprints, - import_snapshot, - read_source, - target_snapshot, -) -from inkcre_extension_registry.service import database as db - - -async def check_import() -> None: - date = "2026-01-02 03:04:05" - with tempfile.TemporaryDirectory(prefix="registry-d1-import-") as directory: - path = Path(directory) / "snapshot.sqlite" - with sqlite3.connect(path) as source: - source.executescript( - (Path(__file__).resolve().parents[1] / "migrations/0001_registry.sql").read_text() - ) - rows = { - "namespaces": [{"name": "migration", "created_at": date}], - "credentials": [ - { - "token_hash": "a" * 64, - "namespace": "migration", - "label": "撤销 ' ? --", - "disabled": 1, - "created_at": date, - } - ], - "extensions": [ - { - "name": "migration/extension", - "namespace": "migration", - "nickname": "迁移", - "publisher_metadata_json": '{"owner": "保留", "nested": {"a": [1, true]}}', - "created_at": date, - } - ], - "releases": [ - { - "extension_name": "migration/extension", - "version": f"1.{i}.0", - "state": state, - "yank_reason": "保留撤回原因" if state == "yanked" else None, - "created_at": date, - "published_at": None if state == "preparing" else date, - "updated_at": date, - } - for i, state in enumerate(("preparing", "published", "yanked", "blocked")) - ], - "python_distributions": [ - { - "extension_name": "migration/extension", - "release_version": "1.2.0", - "normalized_project": "migration-extension", - "project_version": "1.2.0", - "host_sdk": "core-py", - "host_sdk_range": "^1.0.0", - "entry_group": "extensions", - "entry_name": "migration", - "entry_object": "migration:Extension", - "source_repository": "https://example.invalid/repo", - "source_revision": "' ? --", - "build_id": None, - "created_at": date, - } - ], - "module_federation_distributions": [ - { - "extension_name": "migration/extension", - "release_version": "1.2.0", - "host_sdk": "@inkcre/core", - "host_sdk_range": "^1.0.0", - "source_repository": "https://example.invalid/repo", - "source_revision": "abcdef", - "build_id": "build-1", - "manifest_r2_key": "unchanged/mf-manifest.json", - "asset_paths_json": '["mf-manifest.json", "assets/remoteEntry.js"]', - "internal_snapshot_hash": "b" * 64, - "created_at": date, - "uploaded_at": date, - } - ], - "python_files": [ - { - "normalized_project": "migration-extension", - "project_version": "1.2.0", - "filename": "migration_extension-1.2.0-py3-none-any.whl", - "sha256": "c" * 64, - "size": 123, - "filetype": "bdist_wheel", - "requires_python": ">=3.12", - "core_metadata_sha256": "d" * 64, - "r2_key": "unchanged/wheel", - "metadata_r2_key": "unchanged/metadata", - "uploaded_at": date, - } - ], - } - for table, records in rows.items(): - for row in records: - columns = ", ".join(row) - placeholders = ", ".join("?" for _ in row) - source.execute( - f"INSERT INTO {table} ({columns}) VALUES ({placeholders})", - tuple(row.values()), - ) - expected = read_source(path) - invalid = copy.deepcopy(expected) - invalid["python_files"][0]["size"] = -1 - try: - await import_snapshot(invalid) - except IntegrityError: - pass - else: - raise AssertionError("Invalid file metadata must fail the import") - assert not await db.Namespace.exists(), "Failed import left partial identities" - assert await import_snapshot(expected) == fingerprints(expected) - assert await db.Release.all().count() == 4 - assert (await db.Credential.get()).disabled - assert (await db.PythonFile.get()).r2_key == "unchanged/wheel" - try: - await import_snapshot(expected) - except ValueError as error: - assert "empty target" in str(error) - else: - raise AssertionError("Import must refuse an occupied target") - assert fingerprints(await target_snapshot()) == fingerprints(expected) - print("D1 import preserved every field, reference, timestamp, credential and state.") diff --git a/scripts/check_registry.py b/scripts/check_registry.py index aaad5ac..f96154e 100644 --- a/scripts/check_registry.py +++ b/scripts/check_registry.py @@ -18,7 +18,6 @@ import httpx import psycopg -from check_d1_import import check_import from check_documentation import check_documentation from moto.server import ThreadedMotoServer from registry_database import configure_runtime_login @@ -435,23 +434,6 @@ async def main() -> None: transport=httpx.ASGITransport(app=app), base_url="http://localhost", timeout=30 ) as client: await journey(client, token, other_token, app.state.repository.artifacts) - for model in reversed( - ( - db.Namespace, - db.Credential, - db.Extension, - db.Release, - db.NativeRelease, - db.ModuleFederationDistribution, - db.PythonDistribution, - db.PythonFile, - db.DocumentationSnapshot, - db.DocumentationSet, - ) - ): - await model.all().delete() - await check_import() - print("Registry PostgreSQL migrations, transactions, HTTP and S3 checks passed.") finally: for model in ( db.DocumentationSet, @@ -468,6 +450,7 @@ async def main() -> None: await model.all().delete() finally: server.stop() + print("Registry PostgreSQL migrations, transactions, HTTP and S3 checks passed.") if __name__ == "__main__": diff --git a/src/inkcre_extension_registry/import_d1.py b/src/inkcre_extension_registry/import_d1.py deleted file mode 100644 index bd14b5b..0000000 --- a/src/inkcre_extension_registry/import_d1.py +++ /dev/null @@ -1,207 +0,0 @@ -"""Import a read-only D1 SQLite snapshot into an empty migrated PostgreSQL database.""" - -from __future__ import annotations - -import argparse -import asyncio -import hashlib -import json -import os -import sqlite3 -from datetime import UTC, datetime -from pathlib import Path -from urllib.parse import quote - -from tortoise.context import TortoiseContext -from tortoise.transactions import in_transaction - -from .service import database as db -from .service.settings import database_config - -MODELS = ( - db.Namespace, - db.Credential, - db.Extension, - db.Release, - db.PythonDistribution, - db.ModuleFederationDistribution, - db.PythonFile, -) - - -def normalized(row: dict) -> dict: - result = {} - for key, value in row.items(): - if key.endswith("_json"): - key, value = key.removesuffix("_json"), json.loads(value) if value else None - if key.endswith("_at") and value is not None: - date = datetime.fromisoformat(value) if isinstance(value, str) else value - value = date.replace(tzinfo=date.tzinfo or UTC).astimezone(UTC).isoformat() - if key == "disabled": - value = bool(value) - result[key] = value - return result - - -def read_source(path: Path) -> dict[str, list[dict]]: - with sqlite3.connect(f"file:{quote(str(path.resolve()))}?mode=ro", uri=True) as source: - source.row_factory = sqlite3.Row - if source.execute("PRAGMA quick_check").fetchone()[0] != "ok": - raise ValueError("SQLite snapshot integrity check failed") - if source.execute("PRAGMA foreign_key_check").fetchone(): - raise ValueError("SQLite snapshot has broken references") - # Table names are fixed model metadata, never user input. SQL exists only - # at this legacy export boundary; all PostgreSQL reads/writes use ORM. - return { - model._meta.db_table: [ - normalized(dict(row)) - for row in source.execute(f'SELECT * FROM "{model._meta.db_table}"') - ] - for model in MODELS - } - - -def fingerprints(data: dict[str, list[dict]]) -> dict: - return { - table: { - "rows": len(rows), - "sha256": hashlib.sha256( - json.dumps( - sorted(json.dumps(row, sort_keys=True, ensure_ascii=False) for row in rows), - ensure_ascii=False, - ).encode() - ).hexdigest(), - } - for table, rows in data.items() - } - - -async def target_snapshot() -> dict[str, list[dict]]: - data = {model._meta.db_table: await model.all().values() for model in MODELS} - releases = {row["id"]: (row["extension_id"], row["version"]) for row in data["releases"]} - projects = { - row["id"]: (row["normalized_project"], row["project_version"]) - for row in data["python_distributions"] - } - for table, rows in data.items(): - for row in rows: - if "namespace_id" in row: - row["namespace"] = row.pop("namespace_id") - if table == "releases": - row.pop("id") - row.pop("visible_distributions") - row["extension_name"] = row.pop("extension_id") - if "legacy_release_id" in row: - row.pop("id") - row.pop("release_id") - row["extension_name"], row["release_version"] = releases[ - row.pop("legacy_release_id") - ] - if table == "python_files": - row.pop("id") - row["normalized_project"], row["project_version"] = projects[ - row.pop("distribution_id") - ] - data[table] = [normalized(row) for row in rows] - return data - - -async def import_snapshot(source: dict[str, list[dict]]) -> dict: - expected = fingerprints(source) - async with in_transaction(): - for model in MODELS: - if await model.exists(): - raise ValueError( - "Import requires an empty target; it never merges or overwrites data" - ) - releases, projects = {}, {} - for model in MODELS: - for record in source[model._meta.db_table]: - values = record.copy() - if "namespace" in values: - values["namespace_id"] = values.pop("namespace") - if model is db.Release: - values["extension_id"] = values.pop("extension_name") - values["visible_distributions"] = [] - if any( - f["extension_name"] == record["extension_name"] - and f["release_version"] == record["version"] - and any( - p["normalized_project"] == f["normalized_project"] - and p["project_version"] == f["project_version"] - for p in source["python_files"] - ) - for f in source["python_distributions"] - ): - values["visible_distributions"].append("python") - if any( - m["extension_name"] == record["extension_name"] - and m["release_version"] == record["version"] - and m.get("manifest_r2_key") is not None - for m in source["module_federation_distributions"] - ): - values["visible_distributions"].append("module_federation") - elif "extension_name" in values: - values["legacy_release_id"] = releases[ - values.pop("extension_name"), values.pop("release_version") - ] - if model in {db.PythonDistribution, db.ModuleFederationDistribution}: - legacy = await db.Release.get(pk=values["legacy_release_id"]) - kind = "python" if model is db.PythonDistribution else "module_federation" - complete = ( - any( - f["normalized_project"] == record["normalized_project"] - and f["project_version"] == record["project_version"] - for f in source["python_files"] - ) - if kind == "python" - else values.get("manifest_r2_key") is not None - ) - native = await db.NativeRelease.create( - extension_id=legacy.extension_id, - distribution=kind, - version=legacy.version, - state="preparing" - if legacy.state in {"published", "yanked"} and not complete - else legacy.state, - yank_reason=legacy.yank_reason, - created_at=legacy.created_at, - updated_at=legacy.updated_at, - published_at=legacy.published_at, - ) - values["release_id"] = native.pk - if model is db.PythonFile: - values["distribution_id"] = projects[ - values.pop("normalized_project"), values.pop("project_version") - ] - row = await model.create(**values) - if model is db.Release: - releases[record["extension_name"], record["version"]] = row.pk - elif model is db.PythonDistribution: - projects[record["normalized_project"], record["project_version"]] = row.pk - actual = fingerprints(await target_snapshot()) - if actual != expected: - raise ValueError("Imported content differs from source; transaction rolled back") - return actual - - -async def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("snapshot", type=Path) - parser.add_argument("--verify-only", action="store_true") - args = parser.parse_args() - source = read_source(args.snapshot) - url = os.environ.get("MIGRATION_DATABASE_URL") or os.environ["DATABASE_URL"] - async with TortoiseContext() as context: - await context.init(config=database_config(url)) - if args.verify_only: - report = fingerprints(await target_snapshot()) - if report != fingerprints(source): - raise ValueError("Target differs from the source snapshot") - else: - report = await import_snapshot(source) - print(json.dumps(report, indent=2)) - - -if __name__ == "__main__": - asyncio.run(main())