Expire GTD orders before matching, reads and recovery

This commit is contained in:
2026-12-03 04:05:29 +08:00
parent 3bff1c0bc3
commit d43c958ff2
10 changed files with 220 additions and 19 deletions
+38
View File
@@ -0,0 +1,38 @@
use crate::book::{release, CancelReason};
use anyhow::Result;
use rusqlite::{Connection, Transaction, TransactionBehavior};
/// Return a snapshot whose live book was current when the snapshot was acquired.
/// Expirations commit separately so a rejected command cannot revive an order.
pub(crate) fn transaction(
db: &Connection,
behavior: TransactionBehavior,
) -> Result<Transaction<'_>> {
loop {
let tx = Transaction::new_unchecked(db, behavior)?;
let due: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM order_deadlines WHERE pending=1 AND expiration<=unixepoch()+60)",
[], |row| row.get(0),
)?;
if !due {
return Ok(tx);
}
tx.rollback()?;
// Recheck after acquiring the write lock. Other engines can also expire a row.
let write = Transaction::new_unchecked(db, TransactionBehavior::Immediate)?;
let mut stmt = write.prepare(
"SELECT d.seq,o.account FROM order_deadlines d JOIN orders o ON o.seq=d.seq
WHERE d.pending=1 AND d.expiration<=unixepoch()+60 ORDER BY d.expiration,d.seq",
)?;
let due = stmt
.query_map([], |row| {
Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
drop(stmt);
for (seq, owner) in due {
release(&write, seq, &owner, CancelReason::Expired)?;
}
write.commit()?;
}
}