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
124 changes: 124 additions & 0 deletions worker/src/db/seeds.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Default seed data (ONE-446).
//
// A freshly initialised install has the whole schema but zero rows in
// `{prefix}search_engines`, which leaves the start page without a usable search
// box. The setup / upgrade path therefore tops that one table up with the five
// engines below — but ONLY while it is empty. As soon as the owner has any
// engine of their own (or deliberately emptied the table) nothing is written.
//
// Idempotency holds on two levels:
// - an emptiness probe (one COUNT) decides whether to write at all;
// - deterministic ids + `INSERT OR IGNORE`, so even two setup requests racing
// between probe and insert cannot create a second copy of the same engine —
// the primary key absorbs the duplicate.
//
// This is deliberately NOT a migration version: the ledger stays the single
// source of truth for the schema, and the seed is data, re-checkable on every
// upgrade without adding a `schema_v2`.

import { nowIso } from "./sql";

/** One default search engine, written verbatim into `{prefix}search_engines`. */
export interface SeedSearchEngine {
/** Stable id: fixed slug, never regenerated, so re-seeding is idempotent. */
id: string;
name: string;
/** `{q}` is the query placeholder substituted by the client. */
urlTemplate: string;
sortOrder: number;
isDefault: boolean;
}

/** Frozen seed set (ONE-446 §冻结接口契约): order 1–5, only Google is default. */
export const SEED_SEARCH_ENGINES: readonly SeedSearchEngine[] = [
{
id: "seed-google",
name: "Google",
urlTemplate: "https://www.google.com/search?q={q}",
sortOrder: 1,
isDefault: true,
},
{
id: "seed-bing",
name: "Bing",
urlTemplate: "https://www.bing.com/search?q={q}",
sortOrder: 2,
isDefault: false,
},
{
id: "seed-duckduckgo",
name: "DuckDuckGo",
urlTemplate: "https://duckduckgo.com/?q={q}",
sortOrder: 3,
isDefault: false,
},
{
id: "seed-baidu",
name: "百度",
urlTemplate: "https://www.baidu.com/s?wd={q}",
sortOrder: 4,
isDefault: false,
},
{
id: "seed-github",
name: "GitHub",
urlTemplate: "https://github.com/search?q={q}",
sortOrder: 5,
isDefault: false,
},
];

/** Table the defaults live in — keeps the `{prefix}` formula in one place. */
export function searchEnginesTable(prefix: string): string {
return `${prefix}search_engines`;
}

export interface SeedSearchEnginesOutcome {
/** `true` only when this call found the table empty and wrote the defaults. */
seeded: boolean;
/** Rows written by this call (0 when the table already had engines). */
inserted: number;
}

/**
* Inserts {@link SEED_SEARCH_ENGINES} into `{prefix}search_engines` when — and
* only when — the table is empty. Any existing row makes this a no-op, so a
* second setup / upgrade run leaves the table byte-identical.
*/
export async function seedSearchEngines(
db: D1Database,
prefix: string,
): Promise<SeedSearchEnginesOutcome> {
const table = searchEnginesTable(prefix);

const existing = await db
.prepare(`SELECT COUNT(*) AS count FROM ${table}`)
.first<{ count: number }>();
// `?? 0` also covers a driver returning no row for the aggregate.
if ((existing?.count ?? 0) > 0) return { seeded: false, inserted: 0 };

const now = nowIso();
const placeholders = SEED_SEARCH_ENGINES.map(
() => "(?, ?, ?, ?, ?, ?, ?, ?)",
).join(", ");
const values = SEED_SEARCH_ENGINES.flatMap((engine) => [
engine.id,
engine.name,
engine.urlTemplate,
// icon: optional by contract — no bundled artwork, so NULL.
null,
engine.sortOrder,
engine.isDefault ? 1 : 0,
now,
now,
]);

await db
.prepare(
`INSERT OR IGNORE INTO ${table} (id, name, url_template, icon, sort_order, is_default, created_at, updated_at) VALUES ${placeholders}`,
)
.bind(...values)
.run();

return { seeded: true, inserted: SEED_SEARCH_ENGINES.length };
}
24 changes: 23 additions & 1 deletion worker/src/lib/migrate.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,41 @@
import { getTablePrefix, type Env } from "../types";
import { countUsers } from "../db/queries/users";
import { seedSearchEngines } from "../db/seeds";
import { runMigrations, type RunMigrationsResult } from "./migrations-runner";

// Per-isolate flag: after the first successful run in this Worker isolate the
// schema is guaranteed to exist for the isolate's lifetime, so read paths skip
// the ledger replay entirely (D1 tables persist across requests).
let schemaReady = false;

export interface ApplyMigrationsOptions {
/**
* Top up `{prefix}search_engines` with the default engines when that table is
* empty (ONE-446). Setup and upgrade paths pass `true`; the read-path guard
* (`ensureSchema`) does not, so a table the owner emptied on purpose is never
* re-populated by an ordinary page load.
*/
seedDefaults?: boolean;
}

/**
* Applies pending migrations and marks the isolate schema-ready. Returns the
* per-migration ledger outcome so setup can report what was applied/skipped.
* Idempotent: recorded migrations are skipped, so re-running is cheap.
*
* With `seedDefaults` the default search engines are ensured right after the
* schema exists — that seed is itself a no-op unless the table is empty.
*/
export async function applyMigrations(env: Env): Promise<RunMigrationsResult> {
export async function applyMigrations(
env: Env,
options: ApplyMigrationsOptions = {},
): Promise<RunMigrationsResult> {
const result = await runMigrations(env);
if (options.seedDefaults === true) {
// Uses the prefix the runner resolved (not a second getTablePrefix call) so
// the seed always lands in the schema that was just migrated.
await seedSearchEngines(env.DB, result.prefix);
}
schemaReady = true;
return result;
}
Expand Down
6 changes: 4 additions & 2 deletions worker/src/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,12 @@ authRoutes.post("/setup", async (c) => {
}

// Apply the ledgered migrations (creates {prefix}* tables on first setup) and
// report each migration's outcome in the response.
// report each migration's outcome in the response. This is the initialisation
// path, so it also ensures the default search engines exist (ONE-446).
let migrations: MigrationResult[];
try {
migrations = (await applyMigrations(c.env)).migrations;
migrations = (await applyMigrations(c.env, { seedDefaults: true }))
.migrations;
} catch (err) {
if (err instanceof TablePrefixConflictError) {
return c.json(
Expand Down
7 changes: 6 additions & 1 deletion worker/src/services/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ export type SetupMigrationOutcome =
* Runs ONLY the ledgered migrations (forward-only, idempotent): no user is
* created, no password changed, no table dropped. Both setup endpoints share
* this so their payloads and their 409 conflict shape stay identical.
*
* This is also the «检查并升级数据库» path, so it tops up the default search
* engines when that table is empty (ONE-446) — a no-op on any install that
* already has an engine.
*/
export async function runSetupMigrations(
env: Env,
Expand All @@ -107,7 +111,8 @@ export async function runSetupMigrations(
let migrations: MigrationResult[];

try {
migrations = (await applyMigrations(env)).migrations;
migrations = (await applyMigrations(env, { seedDefaults: true }))
.migrations;
} catch (err) {
if (err instanceof TablePrefixConflictError) {
return {
Expand Down
Loading
Loading