Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .github/scripts/d1-migration-manifest.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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"]
}];
5 changes: 3 additions & 2 deletions .github/scripts/d1-migration-plan.mjs
Original file line number Diff line number Diff line change
@@ -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("'", "''")}'`;
Expand All @@ -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),
Expand Down
43 changes: 43 additions & 0 deletions .github/scripts/generate-schema-manifest.mjs
Original file line number Diff line number Diff line change
@@ -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}`);
}
54 changes: 14 additions & 40 deletions .github/scripts/prepare-d1-migrations.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions .github/workflows/deploy-worker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ frontend/dist/
frontend/demo-dist/
.playwright-cli/
.tmp/
worker/src/generated/

# Android local/build outputs
android/.gradle/
Expand Down
13 changes: 11 additions & 2 deletions frontend/src/admin/navigation.js
Original file line number Diff line number Diff line change
@@ -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 = [
{
Expand Down Expand Up @@ -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
}
];

Expand All @@ -59,5 +67,6 @@ export const adminRouteIcons = {
storage: Database,
invites: UserPlus,
telegram: Send,
site: Settings
site: Settings,
maintenance: Wrench
};
3 changes: 3 additions & 0 deletions frontend/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,9 @@ export default {
adminOverview() {
return request('/admin/overview');
},
adminMaintenance() {
return request('/admin/maintenance');
},
adminStorageScan(cursor = '') {
const query = new URLSearchParams();
if (cursor) {
Expand Down
63 changes: 33 additions & 30 deletions frontend/src/components/admin/AdminSidebar.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script setup>
import { ChevronDown, CircleUserRound, Home, Menu, Search, Settings, X } from '@lucide/vue';
import { computed, ref, watch } from 'vue';
import { computed, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { adminNavigation } from '../../admin/navigation.js';
import { useI18n } from '../../i18n.js';
Expand All @@ -11,7 +11,8 @@ const router = useRouter();
const { locale, t } = useI18n();
const query = ref('');
const mobileOpen = ref(false);
const openGroups = ref(new Set(['invites', 'site']));
// 页面导航与菜单展开分开操作;进入栏目也保持收起,避免挤占其它导航入口。
const openGroups = ref(new Set());

const localizedNavigation = computed(() =>
adminNavigation.map((item) => ({
Expand Down Expand Up @@ -72,16 +73,6 @@ function navigate(location) {
void router.push(location);
}

watch(
() => route.path,
(path) => {
const activeGroup = adminNavigation.find((item) => item.children && path.startsWith(item.to));
if (activeGroup && !openGroups.value.has(activeGroup.id)) {
openGroups.value = new Set([...openGroups.value, activeGroup.id]);
}
},
{ immediate: true }
);
</script>

<template>
Expand Down Expand Up @@ -116,31 +107,43 @@ watch(
v-if="!item.children"
type="button"
class="admin-nav-item"
:class="{ 'admin-nav-item--active': isPrimaryActive(item) }"
:class="{ 'admin-nav-item--active': isPrimaryActive(item), 'admin-nav-item--separated': item.separated }"
:aria-current="isPrimaryActive(item) ? 'page' : undefined"
@click="navigate(item.to)"
>
<component :is="item.icon" :size="19" aria-hidden="true" />
<span>{{ item.label }}</span>
</button>

<section v-else class="admin-nav-group">
<button
type="button"
class="admin-nav-item admin-nav-item--group"
:class="{ 'admin-nav-item--active': isPrimaryActive(item) }"
:aria-expanded="isGroupOpen(item)"
@click="toggleGroup(item.id)"
>
<component :is="item.icon" :size="19" aria-hidden="true" />
<span>{{ item.label }}</span>
<ChevronDown
:size="16"
aria-hidden="true"
:class="{ 'admin-nav-group__chevron--open': isGroupOpen(item) }"
/>
</button>

<div v-show="isGroupOpen(item)" class="admin-nav-group__items">
<div class="admin-nav-group__header">
<button
type="button"
class="admin-nav-item admin-nav-item--group"
:class="{ 'admin-nav-item--active': isPrimaryActive(item) }"
:aria-current="isPrimaryActive(item) ? 'page' : undefined"
@click="navigate(item.to)"
>
<component :is="item.icon" :size="19" aria-hidden="true" />
<span>{{ item.label }}</span>
</button>
<button
type="button"
class="admin-nav-group__toggle"
:aria-expanded="isGroupOpen(item)"
:aria-controls="`admin-nav-children-${item.id}`"
:aria-label="t(isGroupOpen(item) ? 'admin.sidebar.collapseGroup' : 'admin.sidebar.expandGroup', { name: item.label })"
@click="toggleGroup(item.id)"
>
<ChevronDown
:size="16"
aria-hidden="true"
:class="{ 'admin-nav-group__chevron--open': isGroupOpen(item) }"
/>
</button>
</div>

<div v-show="isGroupOpen(item)" :id="`admin-nav-children-${item.id}`" class="admin-nav-group__items">
<button
v-for="child in item.children"
:key="child.id"
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/demo/DemoNavigator.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const pages = [
{ labelKey: 'demo.invites', value: '/admin/invites' },
{ labelKey: 'demo.telegram', value: '/admin/telegram' },
{ labelKey: 'demo.site', value: '/admin/site' },
{ labelKey: 'admin.nav.maintenance', value: '/admin/maintenance' },
{ labelKey: 'demo.login', value: '/login' },
{ labelKey: 'demo.register', value: '/register/demo-invite' }
];
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/demo/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
storeDemoFile
} from './state.js';

import { demoMaintenanceReport } from './maintenance.ts';

const DEMO_DELAY_MS = 90;

function fail(message, status = 400) {
Expand Down Expand Up @@ -383,6 +385,9 @@ export async function requestDemo(path, options = {}) {
if (method === 'GET' && pathname === '/admin/overview') {
return cloneDemo(adminOverviewPayload());
}
if (method === 'GET' && pathname === '/admin/maintenance') {
return demoMaintenanceReport();
}
if (method === 'GET' && pathname === '/admin/storage/scan') {
return cloneDemo(adminStoragePayload());
}
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/demo/maintenance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import manifest from '../../../worker/src/generated/schema-manifest.json' with { type: 'json' };
import { assessSchema, D1_MIGRATION_LEDGER } from '../../../worker/src/maintenance/schema-contract.ts';

export function demoMaintenanceReport() {
const schema = assessSchema(
manifest,
new Set([...manifest.artifacts, `table:${D1_MIGRATION_LEDGER}`]),
new Map(manifest.migrations.map((migration) => [migration.id, migration.checksum]))
);
return {
demo: true, checkedAt: new Date().toISOString(), durationMs: 0, status: 'ok',
version: `v${manifest.version}`, expectedMigration: schema.expectedMigration,
checks: ['d1', 'schema', 'sessions', 'files', 'channelRoom', 'userInbox', 'scheduler', 'environment'].map((id) => ({
id, status: 'ok', code: 'ok', durationMs: 0, ...(id === 'schema' ? { schema } : {})
})),
environment: [{ name: 'EDGECHAT_ENCRYPTION_KEYRING', required: true, present: true }]
};
}
5 changes: 5 additions & 0 deletions frontend/src/locales/en-US.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { maintenanceEn } from './maintenance.ts';

export default {
...maintenanceEn,
'app.description': 'Edgechat team communication and collaboration space',
'language.switchToEnglish': 'Switch to English',
'language.switchToChinese': 'Switch to Chinese',
Expand Down Expand Up @@ -249,6 +252,8 @@ export default {
'admin.sidebar.brand': 'Edgechat Admin',
'admin.sidebar.collapseNavigation': 'Collapse admin navigation',
'admin.sidebar.expandNavigation': 'Expand admin navigation',
'admin.sidebar.expandGroup': 'Expand {name} submenu',
'admin.sidebar.collapseGroup': 'Collapse {name} submenu',
'admin.sidebar.searchNavigation': 'Search admin navigation',
'admin.sidebar.search': 'Search',
'admin.sidebar.navigation': 'Admin navigation',
Expand Down
Loading
Loading