diff --git a/.github/scripts/d1-migration-manifest.mjs b/.github/scripts/d1-migration-manifest.mjs index 7fa7b095..1284a03e 100644 --- a/.github/scripts/d1-migration-manifest.mjs +++ b/.github/scripts/d1-migration-manifest.mjs @@ -100,7 +100,7 @@ export const D1_MIGRATIONS = [ "table:device_sessions", "table:realtime_tickets", "table:message_events", - "index:idx_messages_client_message", + // 此索引已被下一次迁移替换;不能再要求最终 schema 保留,否则全新安装无法登记基线。 "index:idx_uploaded_files_client_upload", "index:idx_device_sessions_refresh_token", "index:idx_device_sessions_user_installation_active", @@ -148,3 +148,11 @@ export const D1_MIGRATIONS = [ ], }, ]; + +// b3f6855 曾发布、0c13e8f 已撤回的迁移:仅识别历史 ledger,不要求新安装创建废弃表,也不删除旧数据。 +// 保留当时 LF/CRLF 的精确校验值,不能把所有早于当前版本的未知迁移一律当成正常。 +export const D1_RETIRED_MIGRATIONS = [{ + id: "2026-08-10-server-encryption", + checksum: "c9af2652aa817120a1b2b06230f4c8bd487b96da94579dbc22914e7457209393", + compatibleChecksums: ["e2139b1aeded7c3214b39fa6d9b92db4c93c700f34fba3d696f3ca489111b6bb"] +}]; diff --git a/.github/scripts/d1-migration-plan.mjs b/.github/scripts/d1-migration-plan.mjs index 9dc93dcb..6f960ee1 100644 --- a/.github/scripts/d1-migration-plan.mjs +++ b/.github/scripts/d1-migration-plan.mjs @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; -export const D1_MIGRATION_LEDGER = "edgechat_schema_migrations"; +import { D1_MIGRATION_LEDGER } from "../../worker/src/maintenance/schema-contract.ts"; +export { D1_MIGRATION_LEDGER }; function sqlString(value) { return `'${String(value).replaceAll("'", "''")}'`; @@ -14,7 +15,7 @@ function normalizedMigrationSql(sql) { return sql.replaceAll("\r\n", "\n").replaceAll("\r", "\n"); } -function migrationChecksums(sql) { +export function migrationChecksums(sql) { const normalizedSql = normalizedMigrationSql(sql); return { current: checksum(normalizedSql), diff --git a/.github/scripts/generate-schema-manifest.mjs b/.github/scripts/generate-schema-manifest.mjs new file mode 100644 index 00000000..0c1d29b4 --- /dev/null +++ b/.github/scripts/generate-schema-manifest.mjs @@ -0,0 +1,43 @@ +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; +import initSqlJs from 'sql.js'; +import { collectSchemaArtifacts } from '../../worker/src/maintenance/schema-contract.ts'; +import { D1_MIGRATIONS, D1_RETIRED_MIGRATIONS } from './d1-migration-manifest.mjs'; +import { migrationChecksums } from './d1-migration-plan.mjs'; + +const root = new URL('../../', import.meta.url); +const read = (path) => readFileSync(new URL(path, root), 'utf8'); + +export async function generateSchemaManifest() { + const SQL = await initSqlJs(); + const db = new SQL.Database(); + try { + const schema = read('worker/schema.sql').replaceAll('\r\n', '\n').replaceAll('\r', '\n'); + // 使用真实 SQLite 执行完整 schema,避免正则解析 DDL,也不额外维护表/列/索引清单。 + db.exec(schema); + const artifacts = await collectSchemaArtifacts(async (sql) => { + const result = db.exec(sql)[0]; + return result ? result.values.map((values) => Object.fromEntries(result.columns.map((column, index) => [column, values[index]]))) : []; + }); + return { + version: JSON.parse(read('package.json')).version, + schemaHash: createHash('sha256').update(schema).digest('hex'), + artifacts: [...artifacts].sort(), + retiredMigrations: D1_RETIRED_MIGRATIONS, + migrations: D1_MIGRATIONS.map((migration) => { + const checksums = migrationChecksums(read(migration.file)); + return { id: migration.id, checksum: checksums.current, compatibleChecksums: [...checksums.compatible].sort() }; + }) + }; + } finally { + db.close(); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const manifest = await generateSchemaManifest(); + mkdirSync(new URL('worker/src/generated/', root), { recursive: true }); + writeFileSync(new URL('worker/src/generated/schema-manifest.json', root), `${JSON.stringify(manifest, null, 2)}\n`); + console.log(`Schema manifest: ${manifest.artifacts.length} artifacts, ${manifest.migrations.at(-1).id}`); +} diff --git a/.github/scripts/prepare-d1-migrations.mjs b/.github/scripts/prepare-d1-migrations.mjs index 95ef28fe..935e5ca9 100644 --- a/.github/scripts/prepare-d1-migrations.mjs +++ b/.github/scripts/prepare-d1-migrations.mjs @@ -4,8 +4,10 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { D1_MIGRATIONS } from "./d1-migration-manifest.mjs"; -import { buildD1MigrationPlan, D1_MIGRATION_LEDGER } from "./d1-migration-plan.mjs"; +import { buildD1MigrationPlan } from "./d1-migration-plan.mjs"; import { D1_REPAIRS } from "./d1-repair-manifest.mjs"; +import { collectSchemaArtifacts, collectAppliedMigrations, inspectSchema, schemaTables } from "../../worker/src/maintenance/schema-contract.ts"; +import { generateSchemaManifest } from "./generate-schema-manifest.mjs"; const API_BASE_URL = "https://api.cloudflare.com/client/v4"; const OUTPUT_PATH = ".tmp/edgechat-d1-migrations.sql"; @@ -52,47 +54,19 @@ async function queryD1(sql) { return payload.result?.[0]?.results ?? []; } -async function collectArtifacts() { - const artifacts = new Set(); - const objects = await queryD1( - "SELECT type, name FROM sqlite_master WHERE type IN ('table', 'trigger', 'index')", - ); - - for (const object of objects) { - artifacts.add(`${object.type}:${object.name}`); - } - - const inspectedTables = new Set( - D1_MIGRATIONS.flatMap((migration) => migration.artifacts) - .filter((artifact) => artifact.startsWith("column:")) - .map((artifact) => artifact.slice("column:".length).split(".")[0]), - ); - - for (const table of inspectedTables) { - // D1 REST API 禁止直接执行 PRAGMA,使用等价表值函数才能在 CI 中安全读取列结构。 - const escapedTable = table.replaceAll("'", "''"); - const columns = await queryD1(`SELECT name FROM pragma_table_info('${escapedTable}')`); - for (const column of columns) { - artifacts.add(`column:${table}.${column.name}`); +async function main() { + const manifest = await generateSchemaManifest(); + if (process.argv.includes("--verify")) { + const result = await inspectSchema(queryD1, manifest); + if (result.status !== "ok") { + throw new Error(`D1 schema verification failed: ${JSON.stringify(result)}`); } + console.log(`D1 schema verified: ${result.expectedMigration}`); + return; } - - return artifacts; -} - -async function collectAppliedMigrations(artifacts) { - if (!artifacts.has(`table:${D1_MIGRATION_LEDGER}`)) { - return new Map(); - } - const rows = await queryD1( - `SELECT migration_id, checksum FROM ${D1_MIGRATION_LEDGER} ORDER BY migration_id`, - ); - return new Map(rows.map((row) => [String(row.migration_id), String(row.checksum)])); -} - -async function main() { - const artifacts = await collectArtifacts(); - const appliedMigrations = await collectAppliedMigrations(artifacts); + // D1 的内部表可出现在 sqlite_master,但不允许读取列;只查询应用 manifest 中的表。 + const artifacts = await collectSchemaArtifacts(queryD1, schemaTables(manifest)); + const appliedMigrations = await collectAppliedMigrations(queryD1, artifacts); const plan = await buildD1MigrationPlan({ migrations: D1_MIGRATIONS, repairs: D1_REPAIRS, diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index 674e3157..259b759f 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -85,6 +85,12 @@ jobs: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} run: npx wrangler d1 execute ${{ steps.ensure_resources.outputs.d1_database_name }} --remote --file .tmp/edgechat-d1-migrations.sql --config wrangler.ci.toml + - name: Verify D1 schema contract + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} + EDGECHAT_D1_DATABASE_ID: ${{ steps.ensure_resources.outputs.d1_database_id }} + run: node .github/scripts/prepare-d1-migrations.mjs --verify - name: Generate admin bootstrap SQL (optional) env: EDGECHAT_ADMIN_USERNAME: ${{ secrets.EDGECHAT_ADMIN_USERNAME || secrets.CFCHAT_ADMIN_USERNAME }} diff --git a/.gitignore b/.gitignore index c1e8aa3f..193e1535 100644 --- a/.gitignore +++ b/.gitignore @@ -18,6 +18,7 @@ frontend/dist/ frontend/demo-dist/ .playwright-cli/ .tmp/ +worker/src/generated/ # Android local/build outputs android/.gradle/ diff --git a/frontend/src/admin/navigation.js b/frontend/src/admin/navigation.js index 3f778ecc..e764b0b0 100644 --- a/frontend/src/admin/navigation.js +++ b/frontend/src/admin/navigation.js @@ -1,4 +1,4 @@ -import { Database, Gauge, Send, Settings, UserCog, UserPlus } from '@lucide/vue'; +import { Database, Gauge, Send, Settings, UserCog, UserPlus, Wrench } from '@lucide/vue'; export const adminNavigation = [ { @@ -50,6 +50,14 @@ export const adminNavigation = [ { id: 'site-appearance', labelKey: 'admin.nav.siteAppearance', hash: '#site-appearance' }, { id: 'version-update', labelKey: 'admin.nav.versionUpdate', hash: '#version-update' } ] + }, + { + id: 'maintenance', + labelKey: 'admin.nav.maintenance', + descriptionKey: 'admin.nav.maintenanceDescription', + to: '/admin/maintenance', + icon: Wrench, + separated: true } ]; @@ -59,5 +67,6 @@ export const adminRouteIcons = { storage: Database, invites: UserPlus, telegram: Send, - site: Settings + site: Settings, + maintenance: Wrench }; diff --git a/frontend/src/api.js b/frontend/src/api.js index 5e02846e..92efd927 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -218,6 +218,9 @@ export default { adminOverview() { return request('/admin/overview'); }, + adminMaintenance() { + return request('/admin/maintenance'); + }, adminStorageScan(cursor = '') { const query = new URLSearchParams(); if (cursor) { diff --git a/frontend/src/components/admin/AdminSidebar.vue b/frontend/src/components/admin/AdminSidebar.vue index e0bf6f48..a7706b6a 100644 --- a/frontend/src/components/admin/AdminSidebar.vue +++ b/frontend/src/components/admin/AdminSidebar.vue @@ -1,6 +1,6 @@