Port the simulator to a Rust workspace and document each crate

This commit is contained in:
2026-12-03 02:53:46 +08:00
parent b7579603f9
commit 2f3c699e9c
25 changed files with 1320 additions and 371 deletions
+134
View File
@@ -0,0 +1,134 @@
use exchange::Exchange;
use serde_json::{json, Value};
use std::sync::{Arc, Barrier};
use tempfile::tempdir;
fn setup(e: &mut Exchange) {
for cmd in [
json!({"op":"fund","id":"a","account":"alice","cents":2000}),
json!({"op":"fund","id":"b","account":"bob","cents":2000}),
json!({"op":"list","id":"m","market":"e","rules":"official result"}),
json!({"op":"split","id":"s","market":"e","account":"alice","qty":10}),
] {
e.execute(cmd).unwrap();
}
}
fn order(id: &str, account: &str, side: &str, price: i64, qty: i64) -> Value {
json!({"id":id,"op":"order","account":account,"side":side,"price":price,"qty":qty,"outcome":"YES","market":"e"})
}
fn state(e: &mut Exchange) -> Value {
e.execute(json!({"op":"state"})).unwrap()
}
#[test]
fn auction_fifo_ioc_close_and_redeem() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(order("ask1", "alice", "sell", 40, 2)).unwrap();
e.execute(order("ask2", "alice", "sell", 40, 5)).unwrap();
e.execute(order("bid", "bob", "buy", 60, 4)).unwrap();
assert_eq!(state(&mut e)["fills"], json!([]));
e.execute(json!({"id":"open","op":"open","market":"e"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["fills"],
json!([{"seq":1,"bid":3,"ask":1,"price":40,"quantity":2},{"seq":2,"bid":3,"ask":2,"price":40,"quantity":2}])
);
let mut ioc = order("sweep", "bob", "buy", 45, 6);
ioc["tif"] = json!("IOC");
assert_eq!(
e.execute(ioc).unwrap(),
json!({"order":4,"filled":3,"status":"cancelled"})
);
e.execute(order("rest", "bob", "buy", 10, 8)).unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"resolve","op":"resolve","market":"e","winner":"YES"}))
.unwrap();
let s = state(&mut e);
assert_eq!(
s["accounts"],
json!([{"id":"alice","cash":1580},{"id":"bob","cash":2420}])
);
assert_eq!(s["markets"][0]["collateral"], 0);
}
#[test]
fn retries_reopen_and_no_partial_writes() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let bid = order("repeat", "bob", "buy", 60, 10);
let reply = e.execute(bid.clone()).unwrap();
drop(e);
let mut e = Exchange::open(path).unwrap();
assert_eq!(e.execute(bid).unwrap(), reply);
let before = state(&mut e);
assert!(e.execute(order("repeat", "bob", "buy", 60, 9)).is_err());
assert!(e.execute(order("big", "bob", "buy", 100, 30)).is_err());
assert!(e
.execute(json!({"id":"cancel","op":"cancel","account":"alice","order":1}))
.is_err());
assert_eq!(state(&mut e), before);
e.execute(json!({"id":"cancel","op":"cancel","account":"bob","order":1}))
.unwrap();
e.execute(json!({"id":"close","op":"close","market":"e"}))
.unwrap();
e.execute(json!({"id":"void","op":"resolve","market":"e","winner":"VOID"}))
.unwrap();
assert_eq!(state(&mut e)["accounts"][0]["cash"], 2000);
}
#[test]
fn concurrent_connections_cannot_double_spend() {
let dir = tempdir().unwrap();
let path = dir.path().join("market.db");
let mut e = Exchange::open(&path).unwrap();
setup(&mut e);
let gate = Arc::new(Barrier::new(2));
let workers: Vec<_> = ["first", "second"]
.into_iter()
.map(|id| {
let mut db = Exchange::open(&path).unwrap();
let gate = Arc::clone(&gate);
std::thread::spawn(move || {
gate.wait();
db.execute(order(id, "bob", "buy", 90, 20)).is_ok()
})
})
.collect();
assert_eq!(
workers
.into_iter()
.map(|w| w.join().unwrap())
.filter(|v| *v)
.count(),
1
);
assert_eq!(state(&mut e)["accounts"][1]["cash"], 200);
}
#[test]
fn market_outcome_and_limit_are_isolated() {
let mut e = Exchange::open(":memory:").unwrap();
setup(&mut e);
e.execute(json!({"id":"m2","op":"list","market":"other","rules":"other"}))
.unwrap();
for m in ["e", "other"] {
e.execute(json!({"id":format!("open-{m}"),"op":"open","market":m}))
.unwrap();
}
e.execute(order("ask", "alice", "sell", 65, 7)).unwrap();
for (market, outcome, price) in [("e", "YES", 60), ("e", "NO", 70), ("other", "YES", 70)] {
let mut bid = order(&format!("{market}-{outcome}"), "bob", "buy", price, 3);
bid["market"] = json!(market);
bid["outcome"] = json!(outcome);
bid["tif"] = json!("IOC");
assert_eq!(e.execute(bid).unwrap()["filled"], 0);
}
assert_eq!(state(&mut e)["fills"], json!([]));
}