feat(execution): preserve durable recovery on canonical Rust core
This commit is contained in:
parent
5e9655de0b
commit
c01e96e4dd
27 changed files with 3644 additions and 182 deletions
184
apps/stock/engine/src/api/paper.rs
Normal file
184
apps/stock/engine/src/api/paper.rs
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
//! Stateless trusted durable-host seam. SQL owns custody and commit/publication;
|
||||
//! MatchingAccount owns all financial transitions. No process-resident mutation.
|
||||
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::{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())
|
||||
}
|
||||
// Option fields in checkpoints are required wire fields, including explicit nulls.
|
||||
fn keys_match(input: &Value, typed: &Value) -> bool {
|
||||
match (input, typed) {
|
||||
(Value::Object(a), Value::Object(b)) => {
|
||||
a.len() == b.len()
|
||||
&& a.iter()
|
||||
.all(|(k, v)| b.get(k).is_some_and(|other| keys_match(v, other)))
|
||||
}
|
||||
(Value::Array(a), Value::Array(b)) => {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| keys_match(a, b))
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
fn view(
|
||||
risk: &RiskAccount,
|
||||
orders: &BTreeMap<Id, ManagedOrder>,
|
||||
revision: Counter,
|
||||
) -> Result<Value> {
|
||||
Ok(json!({
|
||||
"admissionRevision": revision,
|
||||
"portfolio": risk.ledger().economic_snapshot(),
|
||||
"equity": risk.ledger().equity().map_err(error)?,
|
||||
"availableCash": risk.available_cash(),
|
||||
"orders": risk.reservations().filter_map(|r|orders.get(&r.order.order_id)).filter(|o|o.status == OrderStatus::Open).collect::<Vec<_>>(),
|
||||
"reservations": risk.reservations().collect::<Vec<_>>(),
|
||||
"risk": risk.state(),
|
||||
}))
|
||||
}
|
||||
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: view(&risk, &orders, before.revision)?,
|
||||
});
|
||||
}
|
||||
if risk.checkpoint() != checkpoint.risk
|
||||
|| orders.into_values().collect::<Vec<_>>() != checkpoint.orders
|
||||
{
|
||||
return Err(error("financial checkpoint reconstruction mismatch"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let final_view = view(
|
||||
account.risk(),
|
||||
&order_map(checkpoint.orders.clone()),
|
||||
checkpoint.revision,
|
||||
)?;
|
||||
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 raw: Value = serde_json::from_str(&input).map_err(error)?;
|
||||
let request: Request = serde_json::from_str(&input).map_err(error)?;
|
||||
if !keys_match(&raw, &serde_json::to_value(&request).map_err(error)?) {
|
||||
return Err(error("unexpected or missing financial transaction fields"));
|
||||
}
|
||||
serde_json::to_string(&stage(request)?).map_err(error)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "paper/tests.rs"]
|
||||
mod tests;
|
||||
Loading…
Add table
Add a link
Reference in a new issue