Port the simulator to a Rust workspace and document each crate
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
mod validation;
|
||||
use validation::identifier;
|
||||
mod book;
|
||||
mod command;
|
||||
mod ledger;
|
||||
mod market;
|
||||
|
||||
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);
|
||||
impl Exchange {
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
|
||||
let 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))
|
||||
}
|
||||
|
||||
pub fn execute(&mut self, payload: Value) -> Result<Value> {
|
||||
if payload == json!({"op":"state"}) {
|
||||
let tx = self.0.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"))?;
|
||||
let names: Vec<String> =
|
||||
stmt.column_names().into_iter().map(str::to_owned).collect();
|
||||
let mut rows = stmt.query([])?;
|
||||
let mut result = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
let mut obj = Map::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
let v = match row.get_ref(i)? {
|
||||
ValueRef::Null => Value::Null,
|
||||
ValueRef::Integer(n) => json!(n),
|
||||
ValueRef::Text(s) => json!(std::str::from_utf8(s)?),
|
||||
_ => anyhow::bail!("unexpected column type"),
|
||||
};
|
||||
obj.insert(name.clone(), v);
|
||||
}
|
||||
result.push(Value::Object(obj));
|
||||
}
|
||||
state.insert(table.into(), Value::Array(result));
|
||||
}
|
||||
tx.commit()?;
|
||||
return Ok(Value::Object(state));
|
||||
}
|
||||
let id = payload["id"].as_str().context("request id required")?;
|
||||
identifier(id)?;
|
||||
let tx = self
|
||||
.0
|
||||
.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let prior: Option<(String, String)> = tx
|
||||
.query_row(
|
||||
"SELECT payload,response FROM requests WHERE id=?",
|
||||
[id],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)
|
||||
.optional()?;
|
||||
if let Some((saved, reply)) = prior {
|
||||
ensure!(
|
||||
serde_json::from_str::<Value>(&saved)? == payload,
|
||||
"request id reused with different content"
|
||||
);
|
||||
return Ok(serde_json::from_str(&reply)?);
|
||||
}
|
||||
let mut body = payload.clone();
|
||||
body.as_object_mut()
|
||||
.context("expected object")?
|
||||
.remove("id");
|
||||
let result = market::apply(&tx, serde_json::from_value(body)?)?;
|
||||
tx.execute(
|
||||
"INSERT INTO requests VALUES(?,?,?)",
|
||||
params![id, payload.to_string(), result.to_string()],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user