e2e-sqlite-readiness.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { DatabaseSync, type SQLInputValue } from "node:sqlite";
  2. interface SqliteReadinessDatabase {
  3. close: () => void;
  4. prepare: (sql: string) => {
  5. get: (...params: SQLInputValue[]) => unknown;
  6. };
  7. }
  8. interface WaitForSqliteTableOptions {
  9. delay?: (ms: number) => Promise<void>;
  10. now?: () => number;
  11. openDatabase?: (databasePath: string) => SqliteReadinessDatabase;
  12. pollIntervalMs?: number;
  13. timeoutMs?: number;
  14. }
  15. const DEFAULT_SQLITE_READINESS_TIMEOUT_MS = 30_000;
  16. const DEFAULT_SQLITE_READINESS_POLL_INTERVAL_MS = 100;
  17. export async function waitForSqliteTable(
  18. databasePath: string,
  19. tableName: string,
  20. options: WaitForSqliteTableOptions = {},
  21. ) {
  22. const delay = options.delay ?? defaultDelay;
  23. const now = options.now ?? Date.now;
  24. const openDatabase = options.openDatabase ?? openReadonlyDatabase;
  25. const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_SQLITE_READINESS_POLL_INTERVAL_MS;
  26. const timeoutMs = options.timeoutMs ?? DEFAULT_SQLITE_READINESS_TIMEOUT_MS;
  27. const startedAt = now();
  28. let lastError = `table ${tableName} 尚未完成 migration`;
  29. while (now() - startedAt <= timeoutMs) {
  30. let database: SqliteReadinessDatabase | null = null;
  31. try {
  32. // Bug 根因:renderer ready 早于 Agent SQLite migration 完成。只用只读方式探测,
  33. // 避免 fixture 抢先创建空 db.sqlite,再让 Agent 在错误的初始状态上跑 migration。
  34. database = openDatabase(databasePath);
  35. const ready = database
  36. .prepare("select 1 as ready from sqlite_master where type = 'table' and name = ?")
  37. .get(tableName);
  38. if (ready) return;
  39. lastError = `table ${tableName} 尚未完成 migration`;
  40. } catch (error) {
  41. lastError = describeError(error);
  42. } finally {
  43. database?.close();
  44. }
  45. if (now() - startedAt >= timeoutMs) break;
  46. await delay(pollIntervalMs);
  47. }
  48. throw new Error(
  49. `SQLite fixture 等待超时: path=${databasePath}, table=${tableName}, lastError=${lastError}`,
  50. );
  51. }
  52. function openReadonlyDatabase(databasePath: string): SqliteReadinessDatabase {
  53. // Node 内置 SQLite 当前只提供同步句柄;这里只做一次 sqlite_master 查询并立即关闭,
  54. // 重试等待本身保持异步,不阻塞事件循环等待文件或 migration。
  55. return new DatabaseSync(databasePath, { readOnly: true });
  56. }
  57. function defaultDelay(ms: number) {
  58. return new Promise<void>((resolve) => setTimeout(resolve, Math.max(0, ms)));
  59. }
  60. function describeError(error: unknown) {
  61. return error instanceof Error ? error.message : String(error);
  62. }