Expire GTD orders before matching, reads and recovery
This commit is contained in:
@@ -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()?;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user