Port the simulator to a Rust workspace and document each crate
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
mod stream;
|
||||
|
||||
use anyhow::{ensure, Context, Result};
|
||||
use exchange::Exchange;
|
||||
use std::{env, io};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = env::args_os().skip(1);
|
||||
let path = args.next().context("usage: eventbook-cli DATABASE")?;
|
||||
ensure!(args.next().is_none(), "usage: eventbook-cli DATABASE");
|
||||
let mut exchange = Exchange::open(path)?;
|
||||
stream::serve(&mut exchange, io::stdin().lock(), io::stdout().lock())
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use anyhow::Result;
|
||||
use exchange::Exchange;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, Write};
|
||||
|
||||
pub(crate) fn serve(
|
||||
engine: &mut Exchange,
|
||||
input: impl BufRead,
|
||||
mut output: impl Write,
|
||||
) -> Result<()> {
|
||||
for line in input.lines() {
|
||||
let line = line?;
|
||||
let result = serde_json::from_str::<Value>(&line)
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|v| engine.execute(v));
|
||||
let reply = result.unwrap_or_else(|e| json!({"error":e.to_string()}));
|
||||
serde_json::to_writer(&mut output, &reply)?;
|
||||
writeln!(output)?;
|
||||
output.flush()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn invalid_line_does_not_discard_next_request() {
|
||||
let mut e = Exchange::open(":memory:").unwrap();
|
||||
let mut out = Vec::new();
|
||||
serve(&mut e, &b"broken\n{\"op\":\"state\"}\n"[..], &mut out).unwrap();
|
||||
let replies: Vec<Value> = std::str::from_utf8(&out)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect();
|
||||
assert_eq!(replies.len(), 2);
|
||||
assert!(replies[0]["error"].is_string());
|
||||
assert_eq!(replies[1]["orders"], json!([]));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user