stock-bot/apps/stock/engine/src/api/paper.rs

148 lines
5.3 KiB
Rust

//! Stateless trusted durable-host seam. SQL owns custody and commit/publication;
//! MatchingAccount owns all financial transitions. No process-resident mutation.
use super::canonical::{financial_view, parse};
use crate::financial::{contract::*, matching::*, risk::RiskAccount};
use napi::{Error, Result};
#[cfg(not(test))]
use napi_derive::napi;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Identity {
session_id: Id,
account_id: Id,
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)]
enum Request {
Initialize {
version: Version,
identity: Identity,
config: MatchingConfig,
},
Apply {
version: Version,
identity: Identity,
checkpoint: MatchingCheckpoint,
command: MatchingCommand,
},
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct JournalEntry {
index: Counter,
effect: MatchingEffect,
view_after: Value,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct Response {
version: Version,
identity: Identity,
checkpoint: MatchingCheckpoint,
view: Value,
outcome: Option<MatchingOutcome>,
journal: Vec<JournalEntry>,
}
fn error(error: impl std::fmt::Display) -> Error {
Error::from_reason(error.to_string())
}
fn order_map(orders: impl IntoIterator<Item = ManagedOrder>) -> BTreeMap<Id, ManagedOrder> {
orders
.into_iter()
.map(|order| (order.order.order_id.clone(), order))
.collect()
}
fn stage(request: Request) -> Result<Response> {
let (identity, mut account, command) = match request {
Request::Initialize {
identity, config, ..
} => (
identity,
MatchingAccount::new(config).map_err(error)?.0,
None,
),
Request::Apply {
identity,
checkpoint,
command,
..
} => (
identity,
MatchingAccount::restore(checkpoint).map_err(error)?.0,
Some(command),
),
};
let before = account.checkpoint();
if before.config.risk.ledger.session_id != identity.session_id
|| before.config.risk.ledger.account_id != identity.account_id
{
return Err(error("financial transaction identity mismatch"));
}
let outcome = command
.as_ref()
.map(|command| account.apply(command).map_err(error))
.transpose()?;
let checkpoint = account.checkpoint();
let mut journal = Vec::new();
if let Some(outcome) = &outcome {
if !outcome.replayed {
// Recovery-only projections: reapply exact retained commands through
// the same risk kernel. Never approximate intermediate state in TS.
let (mut risk, authority) = RiskAccount::restore(before.risk).map_err(error)?;
let mut orders = order_map(before.orders);
for (index, effect) in outcome.effects.iter().enumerate() {
let reproduced = match effect {
MatchingEffect::Risk { command, outcome } => {
Some((risk.apply(command).map_err(error)?, outcome))
}
MatchingEffect::Operator { command, outcome } => {
Some((risk.reset(&authority, command).map_err(error)?, outcome))
}
MatchingEffect::Order(order) => {
orders.insert(order.order.order_id.clone(), order.clone());
None
}
};
if reproduced.is_some_and(|(actual, expected)| actual != *expected) {
return Err(error("financial effect reconstruction mismatch"));
}
journal.push(JournalEntry {
index: (index as u64).try_into().map_err(error)?,
effect: effect.clone(),
view_after: financial_view(&risk, before.revision, |id| orders.get(id))?,
});
}
if risk.checkpoint() != checkpoint.risk
|| orders.into_values().collect::<Vec<_>>() != checkpoint.orders
{
return Err(error("financial checkpoint reconstruction mismatch"));
}
}
}
let final_view = financial_view(account.risk(), checkpoint.revision, |id| account.order(id))?;
Ok(Response {
version: Version,
identity,
checkpoint,
view: final_view,
outcome,
journal,
})
}
/// The caller persists the returned checkpoint/journal atomically before publish.
/// Failed outcomes carry a valid terminal prefix to persist; Err returns no state.
/// Replayed outcomes retain the original receipt but always emit an empty journal.
#[cfg_attr(not(test), napi)]
pub fn stage_financial_transaction(input: String) -> Result<String> {
let request: Request = parse(&input, "unexpected or missing financial transaction fields")?;
serde_json::to_string(&stage(request)?).map_err(error)
}
#[cfg(test)]
#[path = "paper/tests.rs"]
mod tests;