use std::{env, error::Error, io, process, time::Duration}; use rusqlite::{Connection, OptionalExtension, TransactionBehavior}; fn main() -> Result<(), Box> { let mut args = env::args_os().skip(1); let db_path = args .next() .ok_or_else(|| io::Error::other("DB path is required"))?; let crash = args .next() .is_some_and(|arg| arg == "--crash-before-commit"); // Node が作った実験用データベースに別プロセスから接続する。 let mut db = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE)?; db.busy_timeout(Duration::from_secs(3))?; db.execute_batch("PRAGMA foreign_keys = ON;")?; let mut processed = 0; loop { // 書き込みロックを先に取り、別のワーカーと同じ未処理ジョブを拾わない。 let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?; let reservation_id = tx .query_row( "SELECT reservation_id FROM outbox WHERE done = 0 ORDER BY reservation_id LIMIT 1", [], |row| row.get::<_, i64>(0), ) .optional()?; let Some(reservation_id) = reservation_id else { break; }; // 予約IDを主キーにし、予約ごとに処理記録を1件だけ残す。 tx.execute( "INSERT INTO receipts (reservation_id) VALUES (?1) ON CONFLICT(reservation_id) DO NOTHING", [reservation_id], )?; // 接続を閉じる処理を飛ばして異常終了し、未コミットの書き込みを残す。 if crash { process::exit(23); } // 処理記録とジョブ完了を同じトランザクションで確定する。 tx.execute( "UPDATE outbox SET done = 1 WHERE reservation_id = ?1", [reservation_id], )?; tx.commit()?; processed += 1; } // 制御側は終了コードと処理件数を実験結果に表示する。 println!("{processed}"); Ok(()) }