Keep per-instrument order books in memory and recover committed orders
This commit is contained in:
@@ -4,25 +4,33 @@ mod book;
|
||||
mod command;
|
||||
mod ledger;
|
||||
mod market;
|
||||
mod resident;
|
||||
use resident::Books;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use rusqlite::{params, types::ValueRef, Connection, OptionalExtension, TransactionBehavior};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::{path::Path, time::Duration};
|
||||
|
||||
pub struct Exchange(Connection);
|
||||
pub struct Exchange {
|
||||
db: Connection,
|
||||
books: Books,
|
||||
}
|
||||
impl Exchange {
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let db = Connection::open(path)?;
|
||||
let mut db = Connection::open(path)?;
|
||||
db.busy_timeout(Duration::from_secs(10))?;
|
||||
db.execute_batch("PRAGMA foreign_keys=ON")?;
|
||||
db.execute_batch(include_str!("schema.sql"))?;
|
||||
Ok(Self(db))
|
||||
let tx = db.transaction()?;
|
||||
let books = Books::recover(&tx)?;
|
||||
tx.commit()?;
|
||||
Ok(Self { db, books })
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
if payload == json!({"op":"state"}) {
|
||||
let tx = self.0.transaction()?;
|
||||
let tx = self.db.transaction()?;
|
||||
let mut state = Map::new();
|
||||
for table in ["accounts", "markets", "positions", "orders", "fills"] {
|
||||
let mut stmt = tx.prepare(&format!("SELECT * FROM {table} ORDER BY rowid"))?;
|
||||
@@ -51,7 +59,7 @@ impl Exchange {
|
||||
let id = payload["id"].as_str().context("request id required")?;
|
||||
identifier(id)?;
|
||||
let tx = self
|
||||
.0
|
||||
.db
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let prior: Option<(String, String)> = tx
|
||||
.query_row(
|
||||
@@ -71,12 +79,17 @@ impl Exchange {
|
||||
body.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("id");
|
||||
let result = market::apply(&tx, serde_json::from_value(body)?)?;
|
||||
let command = serde_json::from_value(body)?;
|
||||
let external = self.books.changes(&tx)?;
|
||||
self.books.apply(external);
|
||||
let result = market::apply(&tx, &self.books, command)?;
|
||||
tx.execute(
|
||||
"INSERT INTO requests VALUES(?,?,?)",
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
let changes = self.books.changes(&tx)?;
|
||||
tx.commit()?;
|
||||
self.books.apply(changes);
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user