refactor(engine): share strict native financial views (CL18)
This commit is contained in:
parent
580a6de75c
commit
03518c8ae4
9 changed files with 252 additions and 99 deletions
|
|
@ -1,9 +1,9 @@
|
|||
//! Trusted host-only NAPI adapter. The TS loader authenticates D01 data with
|
||||
//! validateDatasetV2; this envelope binds identity but is not a second normalizer
|
||||
//! or an untrusted-code sandbox. No mutable financial/clock handles are exported.
|
||||
use super::canonical::{financial_view, parse as parse_contract};
|
||||
use crate::financial::{
|
||||
contract::*,
|
||||
matching::OrderStatus,
|
||||
replay::*,
|
||||
reporting::ReportingFacts,
|
||||
result::{project, FinancialProjection},
|
||||
|
|
@ -73,28 +73,8 @@ struct ReportResult<'a> {
|
|||
fn error(error: impl std::fmt::Display) -> Error {
|
||||
Error::from_reason(error.to_string())
|
||||
}
|
||||
// Internal replay types intentionally were not wire contracts. Reject unknown
|
||||
// keys recursively at this adapter without changing their financial semantics.
|
||||
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 parse<T: DeserializeOwned + Serialize>(input: &str) -> Result<T> {
|
||||
let raw: Value = serde_json::from_str(input).map_err(error)?;
|
||||
let typed: T = serde_json::from_str(input).map_err(error)?;
|
||||
if !keys_match(&raw, &serde_json::to_value(&typed).map_err(error)?) {
|
||||
return Err(error("unexpected or missing session contract fields"));
|
||||
}
|
||||
Ok(typed)
|
||||
parse_contract(input, "unexpected or missing session contract fields")
|
||||
}
|
||||
|
||||
pub struct ReplayHost {
|
||||
|
|
@ -296,20 +276,45 @@ impl ReplayHost {
|
|||
|
||||
fn view(replay: &Replay) -> Result<Value> {
|
||||
let matching = replay.financial();
|
||||
Ok(json!({
|
||||
"admissionRevision":matching.admission_revision(),
|
||||
"portfolio":matching.ledger().economic_snapshot(),
|
||||
"equity":matching.ledger().equity().map_err(error)?,
|
||||
"availableCash":matching.risk().available_cash(),
|
||||
"orders":matching.risk().reservations().filter_map(|reservation| matching.order(&reservation.order.order_id)).filter(|order| order.status == OrderStatus::Open).collect::<Vec<_>>(),
|
||||
"reservations":matching.risk().reservations().collect::<Vec<_>>(),
|
||||
"risk":matching.risk().state()
|
||||
}))
|
||||
financial_view(matching.risk(), matching.admission_revision(), |id| {
|
||||
matching.order(id)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::financial::native_paper_tests::stage_financial_transaction;
|
||||
|
||||
// Drive the paper host from the same financial commands as replay. Compare
|
||||
// every published boundary, including open reservations, fills and finish.
|
||||
fn assert_paper_view(replay: &Replay, identity: &Value, paper: &mut Value) {
|
||||
let delivered = paper["checkpoint"]["receipts"].as_array().unwrap().len();
|
||||
for receipt in &replay.financial().receipts()[delivered..] {
|
||||
let crate::financial::matching::MatchingInput::Engine(command) = &receipt.input else {
|
||||
panic!("fixture unexpectedly contains an operator command");
|
||||
};
|
||||
*paper = serde_json::from_str(
|
||||
&stage_financial_transaction(
|
||||
json!({
|
||||
"version": 1,
|
||||
"kind": "apply",
|
||||
"identity": identity,
|
||||
"checkpoint": paper["checkpoint"],
|
||||
"command": command,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(paper["view"], view(replay).unwrap());
|
||||
assert_eq!(
|
||||
paper["checkpoint"],
|
||||
serde_json::to_value(replay.financial().checkpoint()).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_intent_trace_matches_direct_replay_receipts() {
|
||||
|
|
@ -317,11 +322,29 @@ mod tests {
|
|||
// load; compare the NAPI pull transport with direct authoritative replay.
|
||||
let fixture = include_str!("../../../../../test/fixtures/native-replay-load.json");
|
||||
let load: Load = parse(fixture).unwrap();
|
||||
let paper_identity = json!({
|
||||
"sessionId": load.identity.session_id,
|
||||
"accountId": load.config.matching.risk.ledger.account_id,
|
||||
});
|
||||
let mut paper: Value = serde_json::from_str(
|
||||
&stage_financial_transaction(
|
||||
json!({
|
||||
"version": 1,
|
||||
"kind": "initialize",
|
||||
"identity": paper_identity,
|
||||
"config": load.config.matching,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut direct = Replay::new(load.prepared, load.config).unwrap();
|
||||
let mut native = ReplayHost::new(fixture.into()).unwrap();
|
||||
let identity = serde_json::to_value(&load.identity).unwrap();
|
||||
let mut sequence = 0;
|
||||
loop {
|
||||
assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper);
|
||||
let raw = native
|
||||
.advance(json!({"identity":identity,"eventBudget":1}).to_string())
|
||||
.unwrap();
|
||||
|
|
@ -355,6 +378,7 @@ mod tests {
|
|||
ReplayStep::Failed { diagnostic } => panic!("{diagnostic}"),
|
||||
}
|
||||
}
|
||||
assert_paper_view(native.replay.as_ref().unwrap(), &paper_identity, &mut paper);
|
||||
let final_result: Value =
|
||||
serde_json::from_str(&native.finalize(identity.to_string()).unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue