示例工程 38-schema-migrations-concurrency

38-schema-migrations-concurrency/app/shared/contention.ts

typescript · 1.4 KB

import { DatabaseSync } from "node:sqlite";
import { performance } from "node:perf_hooks";
import { removeDbFiles } from "./db";

export type ContentionResult = {
  busyMessage: string;
  busyCode: string;
  waitedMs: number;
  retryOk: boolean;
  at: number;
};

function message(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}

export function probeContention(file: string): ContentionResult {
  removeDbFiles(file);
  const a = new DatabaseSync(file);
  a.exec("PRAGMA journal_mode = WAL;");
  a.exec("CREATE TABLE probe (id INTEGER PRIMARY KEY, v TEXT NOT NULL);");
  const b = new DatabaseSync(file);
  b.exec("PRAGMA busy_timeout = 0;");

  let busyMessage = "";
  let busyCode = "";
  let retryOk = false;
  a.exec("BEGIN IMMEDIATE;");
  a.prepare("INSERT INTO probe (v) VALUES (?)").run("a");
  const started = performance.now();
  try {
    b.prepare("INSERT INTO probe (v) VALUES (?)").run("b");
  } catch (error) {
    busyMessage = message(error);
    busyCode = String((error as { code?: string }).code ?? "");
  }
  const waitedMs = performance.now() - started;
  a.exec("ROLLBACK;");
  try {
    b.prepare("INSERT INTO probe (v) VALUES (?)").run("retry");
    retryOk = true;
  } catch {
    retryOk = false;
  }
  a.close();
  b.close();
  removeDbFiles(file);
  return {
    busyMessage,
    busyCode,
    waitedMs: Number(waitedMs.toFixed(2)),
    retryOk,
    at: Date.now(),
  };
}