import { DatabaseSync } from "node:sqlite"; import { parentPort, workerData } from "node:worker_threads"; type AttemptInput = { dbPath: string; gate: SharedArrayBuffer; strategy: "select-only" | "unique"; request: "A" | "B"; room: string; startsAt: string; }; const options = workerData as AttemptInput; const db = new DatabaseSync(options.dbPath); db.exec("PRAGMA busy_timeout = 3000; PRAGMA foreign_keys = ON;"); try { // 両方の依頼が、同じ部屋・開始時刻の空きを別々の接続から読む。 const row = db.prepare( "SELECT EXISTS(SELECT 1 FROM reservations WHERE room = ? AND starts_at = ?) AS occupied", ).get(options.room, options.startsAt); const observedVacant = row?.occupied === 0; // 両方の読み取りが終わるまで、どちらも書き込みに進めない。 const gate = new Int32Array(options.gate); if (Atomics.add(gate, 0, 1) === 0) { if (Atomics.wait(gate, 0, 1, 5000) === "timed-out") throw new Error("Race partner timed out"); } else { Atomics.notify(gate, 0); } let reservationId: number | null = null; if (options.strategy === "unique" || observedVacant) { db.exec("BEGIN IMMEDIATE"); try { // 制約ありでは、一意インデックスに衝突したときだけ挿入を見送る。 const insert = options.strategy === "unique" ? "INSERT INTO reservations (room, starts_at, request) VALUES (?, ?, ?) ON CONFLICT(room, starts_at) DO NOTHING" : "INSERT INTO reservations (room, starts_at, request) VALUES (?, ?, ?)"; const result = db.prepare(insert).run(options.room, options.startsAt, options.request); if (result.changes === 1) { reservationId = Number(result.lastInsertRowid); // 予約の確定と後続処理の登録をまとめ、片方だけが残る状態を避ける。 db.prepare("INSERT INTO outbox (reservation_id) VALUES (?)").run(reservationId); } db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } parentPort?.postMessage({ request: options.request, observedVacant, reservationId, }); } finally { db.close(); }