From 0a35b393aae583984581847b49b37e8814403170 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 04:28:05 +0000 Subject: [PATCH] flybus: sealing sends, encode-once router, cheaper client hot path (BUS-02) - bus-v1 section 12 amendment 2026-10-02: an rpc.call/rpc.reply/publish attachment may name the sender's own unsealed writer; the router seals its declared prefix on admission (copy outside the state lock), the writer becomes the sender's hold, and with recycle:true the staging allocation comes back as a new writer in the reply. A refused sealing send releases every writer it named. contractDigest changes. - SDK: ArtifactWriter::into_unsealed, Responder::reply_sealing; no rpc.responder.release after an admitted reply; delivery payloads moved, not cloned; Fields without hashing. - Router: every frame encoded once (id spliced at selection); admitted payloads forwarded as pre-encoded JSON instead of deep copies; seal copies via copy_file_range with a sized buffer; client location resolution caches the store directories. - fly-session: result attachments kept as delivered (no artifact.retain round trip per attachment); reply artifacts sealed by the reply that carries them, writers recycled into a capacity-bucketed pool. - tests: sealing.rs; artifacts.rs updated to the amendment. examples/rtt.rs measures a round trip. --- docs/design/session-framework/bus-v1.md | 37 ++ services/flysim/crates/fly-session/src/rpc.rs | 30 +- .../flysim/crates/fly-session/src/worker.rs | 145 +++-- services/flysim/crates/flybus/Cargo.toml | 3 +- services/flysim/crates/flybus/examples/rtt.rs | 257 +++++++++ .../crates/flybus/src/client/handles.rs | 144 ++++- .../flysim/crates/flybus/src/client/mod.rs | 4 +- .../crates/flybus/src/client/reactor.rs | 92 +++- services/flysim/crates/flybus/src/lib.rs | 2 +- .../flysim/crates/flybus/src/router/mod.rs | 41 ++ .../flysim/crates/flybus/src/router/state.rs | 499 +++++++++++++++--- services/flysim/crates/flybus/src/store.rs | 159 +++++- services/flysim/crates/flybus/src/wire.rs | 93 +++- .../flysim/crates/flybus/tests/artifacts.rs | 20 +- .../flysim/crates/flybus/tests/sealing.rs | 146 +++++ 15 files changed, 1493 insertions(+), 179 deletions(-) create mode 100644 services/flysim/crates/flybus/examples/rtt.rs create mode 100644 services/flysim/crates/flybus/tests/sealing.rs diff --git a/docs/design/session-framework/bus-v1.md b/docs/design/session-framework/bus-v1.md index 2ed8cfb..38b97de 100644 --- a/docs/design/session-framework/bus-v1.md +++ b/docs/design/session-framework/bus-v1.md @@ -561,3 +561,40 @@ a staging file, reading a sealed one, up to 256 KiB) run in place rather than on -- on the store's tmpfs a hop to the pool and back costs more than the copy -- and `Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder that needs the bytes kept alive can keep a clone instead of taking a second hold. + +**2026-10-02, BUS-02 (wire change; `contractDigest` changes).** A sending command may seal the +artifacts it attaches. Section 8.1 makes a producer seal (`artifact.seal`, one router round trip) +before any message may name the artifact, and section 5 allocates every artifact afresh +(`artifact.allocate`, another). A participant that replies with media every transition -- the +legacy world a frame, a memory image and an audio chunk, the agent a spike bitset and its feed +status -- paid both for every artifact of every transition, two of them on the transition's +critical path, for answers the router could give as it admits the reply. + +- **Sealing attachments.** In `rpc.call`, `rpc.reply` and `publish`, an attachment's `ownerId` may + be the sender's own writer of `ref.artifactId`, still unsealed. Its `ref` is the reference the + sealed artifact will have: this store, generation 1, the allocation's content type, a null + digest, and a `byteLength` of at most the allocation -- the sealed artifact is the first + `byteLength` staging bytes. As part of admitting the command the router seals each such writer + exactly as `artifact.seal` would (section 8.1: the copy into a fresh sealed inode happens outside + the routing state lock, before anything is admitted, and the connection's later commands wait + for it), the writer becomes the sender's explicit hold on the sealed artifact (as after + `artifact.seal`), and only then is the command admitted as if its sender had sealed first. If a + seal fails, or the command is then refused, nothing is admitted and every writer the command + named is released (with whatever it sealed): the reply carries the refusal, `not-dispatched`. +- **Recycling.** Such a command's body may carry `recycle: true` (a body member of `rpc.call`, + `rpc.reply` and `publish` with at least one sealing attachment, refused otherwise). The router + then keeps each sealed writer's staging file and reissues it as a new writer -- a new + `artifactId`, a new hold `ownerId`, the same allocation and content type -- and the command's + reply value carries `writers: [{name, artifactId, generation, ownerId, writeLocation}]`, one per + attachment it sealed, named by attachment. A writer it cannot reissue (owner budget) is simply + left out. Section 8.1's immutability is unchanged: the sealed bytes are a copy, so a producer + writing into the recycled staging file reaches only the staging inode. +- Nothing else changes: deliveries, ownership roots, credits and quotas are those of the command + with pre-sealed attachments; a sealing attachment counts its sealed copy against the store quota + at admission, as `artifact.seal` counts it at the seal. + +SDK changes of the same slice, no wire change: `ArtifactWriter::into_unsealed` and +`Responder::reply_sealing` (the client side of the above); a reply the router admitted spends the +call's reply authority, so the SDK no longer sends `rpc.responder.release` after one (it was a +no-op command on every call); the router encodes each frame once and forwards an admitted +payload as the bytes it re-encoded once at admission instead of deep-copying it per delivery. diff --git a/services/flysim/crates/fly-session/src/rpc.rs b/services/flysim/crates/fly-session/src/rpc.rs index cf38049..9315f0b 100644 --- a/services/flysim/crates/fly-session/src/rpc.rs +++ b/services/flysim/crates/fly-session/src/rpc.rs @@ -186,29 +186,15 @@ impl SentCall { let result = pending.result().await.map_err(|e| bus_error(method, &e))?; let outcome = SessionRpcOutcome::from_json(&Value::Object(result.outcome().clone())) .map_err(|e| DomainError::invalid(format!("{method}: {e}")))?; - // An independent explicit hold on each wanted attachment, so the handle outlives this - // delivery and can be forwarded to several Commit calls and to publication. The holds - // are independent router round trips, so they are taken concurrently. - let wanted: Vec<(String, flybus::Artifact)> = self - .want_artifacts - .iter() - .filter_map(|name| result.artifact(name).ok().map(|a| (name.clone(), a))) - .collect(); - let retains: Vec<_> = wanted - .into_iter() - .map(|(name, artifact)| { - tokio::spawn(async move { - match artifact.retain().await { - Ok(hold) => (name, hold), - Err(_) => (name, artifact), - } - }) - }) - .collect(); + // Each wanted attachment's handle keeps the result delivery's ownership alive for as long + // as it lives (bus-v1 section 8.3), and a delivery's handle can be forwarded -- to the + // Commit calls and to publication -- like a hold (section 8.2). So the handles are kept + // as delivered: an explicit hold per attachment was a router round trip each, on the + // step's critical path, and an `artifact.release` each later (BUS-02). let mut artifacts = BTreeMap::new(); - for retain in retains { - if let Ok((name, artifact)) = retain.await { - artifacts.insert(name, artifact); + for name in &self.want_artifacts { + if let Ok(artifact) = result.artifact(name) { + artifacts.insert(name.clone(), artifact); } } drop(result); diff --git a/services/flysim/crates/fly-session/src/worker.rs b/services/flysim/crates/fly-session/src/worker.rs index ff52cce..d20ced2 100644 --- a/services/flysim/crates/fly-session/src/worker.rs +++ b/services/flysim/crates/fly-session/src/worker.rs @@ -162,17 +162,23 @@ pub struct HandlerCtx<'a> { pub incoming: &'a Incoming, /// Staging writers allocated ahead for the reply artifacts this worker seals every step. pub(crate) writers: &'a WriterPool, + /// The reply artifacts [`HandlerCtx::seal`] wrote and left for the reply to seal (BUS-02). + pub(crate) unsealed: &'a Mutex>, } -/// Staging writers allocated ahead of need (BUS-01). A bus worker seals the same shapes of reply -/// artifact every step -- the environment a 92,160-byte frame, a 65,536-byte memory image and an -/// audio chunk of one of two lengths, the agent a 17,407-byte spike bitset -- and allocating one -/// is a router round trip on the step's critical path. The pool remembers the last few -/// `(content type, length)` shapes [`HandlerCtx::seal`] asked for and, after each reply, allocates -/// a writer for every remembered shape that has none, off the critical path. A seal that finds a -/// ready writer of its exact shape writes and seals it; one that does not allocates as before. A -/// writer is an artifact like any other: unsealed, it is released when dropped, and the bytes it -/// seals are the bytes written, so nothing a caller sees depends on the pool. +/// Staging writers allocated ahead of need (BUS-01), and handed back by the router after each +/// reply (BUS-02). A bus worker seals the same shapes of reply artifact every step -- the +/// environment a 92,160-byte frame, a 65,536-byte memory image and an audio chunk of one of two +/// lengths, the agent a 17,407-byte spike bitset and its feed status, a JSON document of varying +/// length -- and allocating one is a router round trip. The pool remembers the last few +/// `(content type, capacity)` shapes [`HandlerCtx::seal`] asked for; a capacity is the length +/// rounded up to 4 KiB, so the two audio lengths and every feed status share one writer. A seal +/// takes a ready writer of its content type with room for its bytes, writes them, and leaves +/// the artifact for the reply to seal (bus-v1 section 12 amendment 2026-10-02): the reply +/// recycles each writer's allocation, the pool takes the recycled writers back, and only a shape +/// with no writer is allocated, off the critical path, after the reply. A writer is an artifact +/// like any other: unsealed, it is released when dropped, and the bytes sealed are exactly the +/// bytes written, so nothing a caller sees depends on the pool. #[derive(Default)] pub struct WriterPool { state: Mutex, @@ -182,27 +188,51 @@ pub struct WriterPool { struct PoolState { /// The most recent distinct shapes, newest last. recent: Vec<(String, u64)>, - ready: Vec<((String, u64), flybus::ArtifactWriter)>, + ready: Vec, allocating: Vec<(String, u64)>, } -/// Shapes the pool keeps writers for: an environment's three reply artifacts, with the audio -/// chunk's two lengths, and an agent's one. -const POOL_SHAPES: usize = 4; +/// Shapes the pool keeps writers for: an environment's three reply artifacts and an agent's +/// two, with room to spare. +const POOL_SHAPES: usize = 6; + +/// The allocation a reply artifact of `len` bytes is written into. +fn pool_capacity(len: u64) -> u64 { + len.max(1).div_ceil(4096) * 4096 +} impl WriterPool { fn take(&self, content_type: &str, len: u64) -> Option { let mut st = self.state.lock().expect("never poisoned"); - let shape = (content_type.to_owned(), len); + let shape = (content_type.to_owned(), pool_capacity(len)); if let Some(at) = st.recent.iter().position(|s| *s == shape) { st.recent.remove(at); } else if st.recent.len() >= POOL_SHAPES { let gone = st.recent.remove(0); - st.ready.retain(|(s, _)| *s != gone); + st.ready + .retain(|w| (w.content_type(), w.byte_length()) != (gone.0.as_str(), gone.1)); + } + st.recent.push(shape); + let at = st + .ready + .iter() + .enumerate() + .filter(|(_, w)| w.content_type() == content_type && w.byte_length() >= len) + .min_by_key(|(_, w)| w.byte_length()) + .map(|(at, _)| at)?; + Some(st.ready.swap_remove(at)) + } + + /// Takes back the writers a sealing reply recycled, for the shapes still in use. + fn give(&self, writers: Vec) { + let mut st = self.state.lock().expect("never poisoned"); + for w in writers { + let shape = (w.content_type().to_owned(), w.byte_length()); + let spare = st.ready.iter().any(|r| (r.content_type(), r.byte_length()) == (shape.0.as_str(), shape.1)); + if st.recent.contains(&shape) && !spare { + st.ready.push(w); + } } - st.recent.push(shape.clone()); - let at = st.ready.iter().position(|(s, _)| *s == shape)?; - Some(st.ready.swap_remove(at).1) } /// Allocates, in the background, a writer for every remembered shape that has none. @@ -212,7 +242,10 @@ impl WriterPool { let wanted: Vec<_> = st .recent .iter() - .filter(|s| !st.ready.iter().any(|(r, _)| r == *s) && !st.allocating.contains(s)) + .filter(|s| { + !st.ready.iter().any(|w| (w.content_type(), w.byte_length()) == (s.0.as_str(), s.1)) + && !st.allocating.contains(s) + }) .cloned() .collect(); st.allocating.extend(wanted.iter().cloned()); @@ -227,7 +260,7 @@ impl WriterPool { if let Ok(writer) = writer && st.recent.contains(&shape) { - st.ready.push((shape, writer)); + st.ready.push(writer); } }); } @@ -290,26 +323,36 @@ impl HandlerCtx<'_> { } /// One immutable reply artifact holding `bytes`. Over the local lane it is an in-memory - /// artifact that owns `bytes` (no copy, no store file, no router round trip); over the bus - /// it is allocated, written and sealed in the router's store as before. + /// artifact that owns `bytes` (no copy, no store file, no router round trip). Over the bus + /// the bytes go into a staging writer (one allocated ahead, [`WriterPool`]) and the reply + /// that carries the artifact seals it as the router admits the reply (bus-v1 section 12 + /// amendment 2026-10-02, BUS-02): the handle is valid from then on, and the handler must + /// put it in its reply. pub async fn seal(&self, content_type: &str, bytes: Vec) -> DomainResult { if self.is_local() { return Ok(flybus::Artifact::in_memory(content_type, bytes)); } - // A writer allocated ahead for this shape saves the allocation's round trip ([`WriterPool`]). - let Some(mut writer) = self.writers.take(content_type, bytes.len() as u64) else { - let _span = crate::profile::span("shell.seal.allocated"); - return crate::media::seal_copy(self.client, content_type.to_owned(), &bytes).await; + let len = bytes.len() as u64; + let mut writer = match self.writers.take(content_type, len) { + Some(writer) => writer, + None => { + let _span = crate::profile::span("shell.seal.allocated"); + self.client + .artifacts() + .allocate(pool_capacity(len), content_type) + .await + .map_err(|e| crate::media::store_error("allocate", &e.message))? + } }; let _span = crate::profile::span("shell.seal.pooled"); use std::io::Write as _; writer .write_all(&bytes) .map_err(|e| crate::media::store_error("write", &e.to_string()))?; - writer - .seal() - .await - .map_err(|e| crate::media::store_error("seal", &e.message)) + let unsealed = writer.into_unsealed(); + let artifact = unsealed.artifact().clone(); + self.unsealed.lock().expect("never poisoned").push(unsealed); + Ok(artifact) } } @@ -477,15 +520,30 @@ enum Answer { } impl Answer { - async fn send(self, outcome: SessionRpcOutcome, artifacts: &[(String, flybus::Artifact)]) { + /// Answers the call. Over the bus, the artifacts left unsealed by [`HandlerCtx::seal`] are + /// sealed by the reply itself and their writers come back recycled, for the pool (BUS-02). + async fn send( + self, + outcome: SessionRpcOutcome, + artifacts: &[(String, flybus::Artifact)], + unsealed: Vec, + ) -> Vec { match self { Answer::Bus(responder) => { let list: Vec<(&str, &flybus::Artifact)> = artifacts.iter().map(|(n, a)| (n.as_str(), a)).collect(); - let _ = responder.reply(outcome.to_outcome(), &list).await; + if unsealed.is_empty() { + let _ = responder.reply(outcome.to_outcome(), &list).await; + return Vec::new(); + } + match responder.reply_sealing(outcome.to_outcome(), &list, unsealed, true).await { + Ok(sealed) => sealed.writers, + Err(_) => Vec::new(), + } } Answer::Local(tx) => { let _ = tx.send(LocalReply { outcome, artifacts: artifacts.to_vec() }); + Vec::new() } } } @@ -751,7 +809,7 @@ impl Shell { DomainError::before(ErrorCode::Unsupported, format!("{method} is not supported")), request.scope.clone(), ); - answer.send(outcome, &[]).await; + answer.send(outcome, &[], Vec::new()).await; return; }; @@ -762,7 +820,7 @@ impl Shell { Ok(body) => body, Err(e) => { let outcome = refuse(DomainError::invalid(format!("{method}: {e}")), request.scope.clone()); - answer.send(outcome, &[]).await; + answer.send(outcome, &[], Vec::new()).await; return; } }; @@ -776,7 +834,7 @@ impl Shell { }, (OpClass::StepMutation, None) => { let outcome = refuse(DomainError::invalid(format!("{method} requires a scope")), None); - answer.send(outcome, &[]).await; + answer.send(outcome, &[], Vec::new()).await; return; } _ => OperationKey { @@ -797,12 +855,12 @@ impl Shell { }; match admission { Admission::Replay(reply) => { - answer.send(reply.outcome.clone(), &reply.artifacts).await; + answer.send(reply.outcome.clone(), &reply.artifacts, Vec::new()).await; return; } Admission::Refuse(e) => { let outcome = refuse(e, request.scope.clone()); - answer.send(outcome, &[]).await; + answer.send(outcome, &[], Vec::new()).await; return; } Admission::Execute => {} @@ -907,6 +965,7 @@ async fn execute( let Admitted { class, key, serial, body, method, request, incoming } = admitted; let (worker_id, incarnation_id, status, cache) = (&shell.worker_id, &shell.incarnation_id, &shell.status, &shell.cache); + let unsealed = Mutex::new(Vec::new()); let outcome = { // One mutation at a time: the endpoint mutex is the worker's simulation lock, and it is // never held across a bus round trip taken by anything else. @@ -918,6 +977,7 @@ async fn execute( client: &shell.client, incoming: &incoming, writers: &shell.writers, + unsealed: &unsealed, }; if matches!(incoming, Incoming::Bus(_)) && long_method(&method) && blocking_allowed() { // A long bus request's handler runs with this worker thread handed over to blocking @@ -990,11 +1050,14 @@ async fn execute( status.set_completed(request.request_id.clone()); drop(cache_span); let reply_span = crate::profile::span("shell.reply"); - answer.send(outcome, &reply.artifacts).await; + let unsealed = std::mem::take(&mut *unsealed.lock().expect("never poisoned")); + let recycled = answer.send(outcome, &reply.artifacts, unsealed).await; drop(reply_span); - // The next step's writers, allocated while the caller goes on (bus requests only: - // the lane seals nothing into the store). + // The next step's writers: the ones the reply recycled, and any shape without one + // allocated while the caller goes on (bus requests only: the lane seals nothing into + // the store). if matches!(incoming, Incoming::Bus(_)) { + shell.writers.give(recycled); shell.writers.refill(&shell.client); } } @@ -1027,7 +1090,7 @@ async fn execute( request.scope.clone(), e, ); - answer.send(outcome, &[]).await; + answer.send(outcome, &[], Vec::new()).await; } } } diff --git a/services/flysim/crates/flybus/Cargo.toml b/services/flysim/crates/flybus/Cargo.toml index fc4bcb1..6093f94 100644 --- a/services/flysim/crates/flybus/Cargo.toml +++ b/services/flysim/crates/flybus/Cargo.toml @@ -11,7 +11,8 @@ description = "A small local RPC and pub/sub bus with immutable file-backed arti # `flock`, `posix_fallocate` and `O_NOFOLLOW`; everything else is std or Tokio. libc = "0.2" serde = { workspace = true } -serde_json = { workspace = true } +# `raw_value`: the router forwards payloads it validated as pre-encoded JSON (BUS-02). +serde_json = { workspace = true, features = ["raw_value"] } sha2 = { workspace = true } tokio = { version = "1", features = ["rt", "net", "io-util", "sync", "time", "macros"] } diff --git a/services/flysim/crates/flybus/examples/rtt.rs b/services/flysim/crates/flybus/examples/rtt.rs new file mode 100644 index 0000000..3ca1405 --- /dev/null +++ b/services/flysim/crates/flybus/examples/rtt.rs @@ -0,0 +1,257 @@ +//! Round-trip latency of one RPC through the router, the cost every session transition pays +//! several times (BUS-02). The router and the caller share one process (as the session's +//! router and coordinator do); the service is a child process on a Unix socket (process mode) +//! or a task in the same process over an in-memory pipe (`--in-memory`). +//! +//! ```text +//! cargo run --release -p flybus --example rtt -- [--calls N] [--payload BYTES] [--reply-artifact BYTES] +//! [--router-workers N] [--in-memory] [--read] +//! ``` +//! +//! `--reply-artifact` makes the service seal an artifact of that size into every reply (a +//! writer allocated ahead, as the session's writer pool does) and `--read` makes the caller read +//! it. Prints p50/p90/p99 in microseconds. Local synthetic timings, no capacity claim. + +use std::time::{Duration, Instant}; + +use flybus::{Client, ClientConfig, Policy, Router, RouterConfig, ServiceConfig}; +use serde_json::{Map, Value}; + +#[derive(Clone, Copy)] +struct Opts { + calls: usize, + payload: usize, + reply_artifact: usize, + router_workers: usize, + in_memory: bool, + read: bool, + spawned: bool, + sealing: bool, +} + +fn opts(args: &[String]) -> Opts { + let mut o = Opts { + calls: 2000, + payload: 512, + reply_artifact: 0, + router_workers: 2, + in_memory: false, + read: false, + spawned: false, + sealing: false, + }; + let mut i = 0; + while i < args.len() { + let next = |i: usize| args.get(i + 1).and_then(|v| v.parse::().ok()).unwrap_or(0); + match args[i].as_str() { + "--calls" => { + o.calls = next(i); + i += 1; + } + "--payload" => { + o.payload = next(i); + i += 1; + } + "--reply-artifact" => { + o.reply_artifact = next(i); + i += 1; + } + "--router-workers" => { + o.router_workers = next(i).max(1); + i += 1; + } + "--in-memory" => o.in_memory = true, + "--read" => o.read = true, + "--spawned" => o.spawned = true, + "--sealing" => o.sealing = true, + _ => {} + } + i += 1; + } + o +} + +fn payload(bytes: usize) -> Map { + let mut m = Map::new(); + m.insert("blob".into(), Value::String("x".repeat(bytes))); + m +} + +async fn serve(client: Client, reply_artifact: usize, sealing: bool) { + let mut svc = client.register("bench.echo", ServiceConfig::default()).await.unwrap(); + let mut ahead = None; + while let Some(req) = svc.next().await { + if sealing && reply_artifact > 0 { + // Sealed by the router as it admits the reply; the staging file comes back as the + // next writer (`--sealing`). + let mut w = match ahead.take() { + Some(w) => w, + None => client + .artifacts() + .allocate(reply_artifact as u64, "application/octet-stream") + .await + .unwrap(), + }; + use std::io::Write; + w.write_all(&vec![7u8; reply_artifact]).unwrap(); + let unsealed = w.into_unsealed(); + let blob = unsealed.artifact().clone(); + let out = req + .responder() + .reply_sealing(payload(64), &[("blob", &blob)], vec![unsealed], true) + .await + .unwrap(); + ahead = out.writers.into_iter().next(); + continue; + } + let mut atts = Vec::new(); + if reply_artifact > 0 { + let mut w = match ahead.take() { + Some(w) => w, + None => client + .artifacts() + .allocate(reply_artifact as u64, "application/octet-stream") + .await + .unwrap(), + }; + use std::io::Write; + w.write_all(&vec![7u8; reply_artifact]).unwrap(); + atts.push(("blob", w.seal().await.unwrap())); + } + let refs: Vec<(&str, &flybus::Artifact)> = atts.iter().map(|(n, a)| (*n, a)).collect(); + let _ = req.reply(payload(64), &refs).await; + drop(req); + if reply_artifact > 0 { + ahead = Some( + client + .artifacts() + .allocate(reply_artifact as u64, "application/octet-stream") + .await + .unwrap(), + ); + } + } +} + +fn child(sock: &str, root: &str, reply_artifact: usize, sealing: bool) { + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_all() + .build() + .unwrap(); + // As a session participant serves: on the runtime's one worker, not the blocked main thread. + let (sock, root) = (sock.to_owned(), root.to_owned()); + let handle = rt.handle().clone(); + rt.block_on(async move { + handle + .spawn(async move { + let client = Client::connect_unix(sock, ClientConfig::new("svc", root)).await.unwrap(); + serve(client, reply_artifact, sealing).await; + }) + .await + .unwrap(); + }); +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.first().map(String::as_str) == Some("--child") { + child(&args[1], &args[2], args[3].parse().unwrap(), args[4] == "1"); + return; + } + let o = opts(&args); + let dir = std::env::temp_dir().join(format!("flybus-rtt-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let root = dir.join("store"); + let sock = dir.join("bus.sock"); + let rt = tokio::runtime::Builder::new_multi_thread() + .worker_threads(o.router_workers) + .enable_all() + .build() + .unwrap(); + let spawned = o.spawned; + let (root2, sock2) = (root.clone(), sock.clone()); + let body = async move { + let (root, sock) = (root2, sock2); + let mut child_proc = None; + let mut config = RouterConfig::new(&root); + config.policy = Policy::open(); + let router = Router::new(config).unwrap(); + let _listener = router.listen_unix(&sock).await.unwrap(); + if o.in_memory { + let c = Client::connect(router.connect_in_memory(), ClientConfig::new("svc", &root)) + .await + .unwrap(); + tokio::spawn(serve(c, o.reply_artifact, o.sealing)); + } else { + child_proc = Some( + std::process::Command::new(std::env::current_exe().unwrap()) + .args([ + "--child", + sock.to_str().unwrap(), + root.to_str().unwrap(), + &o.reply_artifact.to_string(), + if o.sealing { "1" } else { "0" }, + ]) + .spawn() + .unwrap(), + ); + } + let caller = Client::connect(router.connect_in_memory(), ClientConfig::new("caller", &root)) + .await + .unwrap(); + // Wait for the service to register. + loop { + match caller.call_and_wait("bench.echo", None, "Echo", payload(8), &[]).await { + Ok(_) => break, + Err(_) => tokio::time::sleep(Duration::from_millis(20)).await, + } + } + let mut samples = Vec::with_capacity(o.calls); + for i in 0..o.calls + 100 { + let t = Instant::now(); + let result = caller + .call_and_wait("bench.echo", None, "Echo", payload(o.payload), &[]) + .await + .unwrap(); + if o.read && o.reply_artifact > 0 { + let a = result.artifact("blob").unwrap(); + let bytes = a.read_all().await.unwrap(); + assert_eq!(bytes.len(), o.reply_artifact); + } + drop(result); + if i >= 100 { + samples.push(t.elapsed()); + } + } + samples.sort(); + let p = |q: f64| samples[((samples.len() - 1) as f64 * q) as usize].as_secs_f64() * 1e6; + println!( + "rtt mode={} sealing={} payload={} reply_artifact={} read={} router_workers={} calls={}: p50={:.0}us p90={:.0}us p99={:.0}us", + if o.in_memory { "in-memory" } else { "process" }, + o.sealing, + o.payload, + o.reply_artifact, + o.read, + o.router_workers, + o.calls, + p(0.5), + p(0.9), + p(0.99) + ); + child_proc + }; + // `--spawned`: the caller runs on a runtime worker, beside the router's tasks, instead of on + // the thread that blocks on the runtime. + let child_proc = if spawned { + let handle = rt.handle().clone(); + rt.block_on(async move { handle.spawn(body).await.unwrap() }) + } else { + rt.block_on(body) + }; + if let Some(mut c) = child_proc { + let _ = c.kill(); + let _ = c.wait(); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/services/flysim/crates/flybus/src/client/handles.rs b/services/flysim/crates/flybus/src/client/handles.rs index 3329393..d9b9d09 100644 --- a/services/flysim/crates/flybus/src/client/handles.rs +++ b/services/flysim/crates/flybus/src/client/handles.rs @@ -12,9 +12,9 @@ use std::sync::Arc; use serde_json::{Map, Value}; use tokio::sync::{mpsc, oneshot}; -use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand}; +use super::reactor::{CallSlot, ClientConn, Control, Extra, Hook, OutCommand, WriterGrant}; use crate::error::{BusError, Dispatch, ErrorCode}; -use crate::store::{open_read, resolve}; +use crate::store::{open_read, open_write, resolve}; use crate::wire::{ArtifactRef, Attachment, Fields, GENERATION, Identity, Location}; pub(crate) struct OwnerGuard { @@ -363,6 +363,8 @@ pub struct ArtifactWriter { pub(crate) artifact_id: String, pub(crate) byte_length: u64, pub(crate) written: u64, + pub(crate) store_id: String, + pub(crate) content_type: String, } impl ArtifactWriter { @@ -374,6 +376,40 @@ impl ArtifactWriter { self.byte_length } + /// Bytes written so far: what a sealing send seals ([`Responder::reply_sealing`]). + pub fn written(&self) -> u64 { + self.written + } + + pub fn content_type(&self) -> &str { + &self.content_type + } + + /// Ends writing and returns the artifact as a sealing send will seal it: its first + /// [`written`](Self::written) bytes, under this writer's owner, which becomes the hold + /// (bus-v1 section 12 amendment 2026-10-02). The handle is usable once a send that attaches + /// it -- [`Responder::reply_sealing`] -- is admitted; before that it is only a name for it. + pub fn into_unsealed(mut self) -> Unsealed { + drop(self.file.take()); + let reference = ArtifactRef { + store_id: self.store_id.clone(), + artifact_id: self.artifact_id.clone(), + generation: GENERATION, + byte_length: self.written, + content_type: self.content_type.clone(), + digest: None, + }; + Unsealed { + artifact: Artifact { + reference: Arc::new(reference), + holder: Holder::Bus(self.owner.clone()), + location: None, + }, + capacity: self.byte_length, + content_type: std::mem::take(&mut self.content_type), + } + } + /// Closes the writable handle and seals, returning the immutable artifact on an explicit /// hold. Bytes not written read as zeros: the staging file is preallocated. pub async fn seal(self) -> Result { @@ -539,6 +575,28 @@ impl Request { } } +/// A writer's artifact waiting for the send that seals it ([`ArtifactWriter::into_unsealed`]). +pub struct Unsealed { + artifact: Artifact, + capacity: u64, + content_type: String, +} + +impl Unsealed { + /// The handle the sealed artifact will have; attach it to the sealing send. + pub fn artifact(&self) -> &Artifact { + &self.artifact + } +} + +/// What a sealing reply ([`Responder::reply_sealing`]) produced. +pub struct SealedReply { + /// As [`Responder::reply`]: routed to the caller, or the caller had detached. + pub routed: bool, + /// With `recycle`, a fresh writer of the same allocation for each artifact sealed. + pub writers: Vec, +} + /// Replies to one request, whether or not the request delivery is still held. #[derive(Clone)] pub struct Responder { @@ -567,18 +625,100 @@ impl Responder { .shared .command("rpc.reply", body, atts, keep, Hook::None) .await?; + // An admitted reply ends this call's reply authority at the router (routed or, for a + // detached caller, retired), so there is nothing left to release (BUS-02): the + // `rpc.responder.release` the guard would send is a no-op command on every call. + self.guard + .replied + .store(true, std::sync::atomic::Ordering::Release); Ok(Fields::of(&reply.value, "reply").boolean("routed")?) } } +impl Responder { + /// Replies with `attachments`, among which the artifacts of `unsealed` are sealed by the + /// router as it admits the reply (bus-v1 section 12 amendment 2026-10-02): each becomes an + /// immutable artifact exactly as if it had been sealed and then attached, without the + /// `artifact.seal` round trip. With `recycle` the router reissues each one's staging + /// allocation as a new writer, which saves the next `artifact.allocate`. Refused, nothing + /// is admitted and every unsealed artifact is gone. + pub async fn reply_sealing( + &self, + outcome: Map, + attachments: &[(&str, &Artifact)], + unsealed: Vec, + recycle: bool, + ) -> Result { + let (atts, keep) = attachment_list(attachments)?; + let shapes: Vec<(String, u64, String)> = unsealed + .into_iter() + .filter_map(|u| { + let name = atts + .iter() + .find(|a| a.reference.artifact_id == u.artifact.reference.artifact_id)? + .name + .clone(); + Some((name, u.capacity, u.content_type)) + }) + .collect(); + let mut body = Map::new(); + body.insert("callId".into(), self.call_id.clone().into()); + body.insert( + "requestDeliveryId".into(), + self.request_delivery_id.clone().into(), + ); + body.insert("outcome".into(), Value::Object(outcome)); + if recycle && !shapes.is_empty() { + body.insert("recycle".into(), true.into()); + } + let shared = &self.guard.conn.shared; + let reply = shared + .command("rpc.reply", body, atts, keep, Hook::Writers) + .await?; + self.guard + .replied + .store(true, std::sync::atomic::Ordering::Release); + let routed = Fields::of(&reply.value, "reply").boolean("routed")?; + let grants = match reply.extra { + Extra::Writers(grants) => grants, + _ => Vec::new(), + }; + let mut writers = Vec::with_capacity(grants.len()); + for WriterGrant { name, artifact_id, owner, location } in grants { + let Some((_, capacity, content_type)) = shapes.iter().find(|(n, _, _)| *n == name) + else { + continue; + }; + let path = resolve(&shared.store_root, &location.store_id, &location)?; + let file = open_write(&path) + .map_err(|e| BusError::new(ErrorCode::StoreFailure, format!("staging: {e}")))?; + writers.push(ArtifactWriter { + file: Some(file), + owner, + artifact_id, + byte_length: *capacity, + written: 0, + store_id: location.store_id, + content_type: content_type.clone(), + }); + } + Ok(SealedReply { routed, writers }) + } +} + pub(crate) struct ReplyGuard { pub conn: Arc, pub call_id: String, pub request_delivery_id: String, + /// Set once the router admitted a reply: the authority is spent, no release is sent. + pub replied: std::sync::atomic::AtomicBool, } impl Drop for ReplyGuard { fn drop(&mut self) { + if self.replied.load(std::sync::atomic::Ordering::Acquire) { + return; + } self.conn.shared.push_control(Control::ResponderReleased { call_id: self.call_id.clone(), request_delivery_id: self.request_delivery_id.clone(), diff --git a/services/flysim/crates/flybus/src/client/mod.rs b/services/flysim/crates/flybus/src/client/mod.rs index 1ef0a80..f641fda 100644 --- a/services/flysim/crates/flybus/src/client/mod.rs +++ b/services/flysim/crates/flybus/src/client/mod.rs @@ -15,7 +15,7 @@ use tokio::sync::oneshot; use handles::attachment_list; pub use handles::{ IN_MEMORY_STORE_ID, Artifact, ArtifactFile, ArtifactWriter, CancelState, Message, PendingCall, Request, Responder, - RpcResult, Service, Subscription, + RpcResult, SealedReply, Service, Subscription, Unsealed, }; use reactor::{CallSlot, ClientConn, Extra, Hook, OutCommand, Shared}; @@ -593,6 +593,8 @@ impl Artifacts<'_> { artifact_id, byte_length, written: 0, + store_id: loc.store_id, + content_type: content_type.to_owned(), }) } } diff --git a/services/flysim/crates/flybus/src/client/reactor.rs b/services/flysim/crates/flybus/src/client/reactor.rs index c9ef972..3446351 100644 --- a/services/flysim/crates/flybus/src/client/reactor.rs +++ b/services/flysim/crates/flybus/src/client/reactor.rs @@ -44,6 +44,17 @@ pub(crate) enum Extra { Service(ServiceGuard, mpsc::UnboundedReceiver), Subscription(SubscriptionGuard, mpsc::UnboundedReceiver), Call(CallGuard), + /// The writers a sealing send's reply reissued (`recycle`), with their owners. + Writers(Vec), +} + +/// One recycled writer a sealing send's reply granted (bus-v1 section 12 amendment +/// 2026-10-02): the attachment it was, and the new artifact its staging file now is. +pub(crate) struct WriterGrant { + pub name: String, + pub artifact_id: String, + pub owner: Arc, + pub location: crate::wire::Location, } /// What the reactor does with a reply before handing it over. Handles are built here, inside @@ -57,6 +68,8 @@ pub(crate) enum Hook { Subscribe, Call(String), Cancel(String), + /// `value.writers`, when present, are new writers (a recycling sealing send). + Writers, } pub(crate) struct OutCommand { @@ -445,6 +458,7 @@ pub(crate) async fn write_loop(shared: Arc, mut wr: WriteHalf _ = shutdown.wait_for(|v| *v) => break, } } + Next::Exit => break, } } @@ -617,6 +631,7 @@ fn validate_reply_value(op: &str, value: &Map) -> Result<(), Wire } "rpc.reply" => { f.boolean("routed")?; + validate_writers(&mut f)?; } "rpc.responder.release" => { f.boolean("released")?; @@ -673,6 +688,29 @@ fn validate_reply_value(op: &str, value: &Map) -> Result<(), Wire f.finish() } +/// The optional `writers` of a sealing send's reply (bus-v1 section 12 amendment 2026-10-02). +fn validate_writers(f: &mut Fields<'_>) -> Result<(), WireError> { + let Some(list) = f.optional("writers") else { + return Ok(()); + }; + let list = list + .as_array() + .filter(|l| (1..=crate::wire::MAX_ATTACHMENTS).contains(&l.len())) + .ok_or_else(|| WireError("writers must be an array of 1..=32 grants".into()))?; + for w in list { + let mut g = Fields::new(w, "writer")?; + g.id("name")?; + serial_field(&mut g, "artifactId", "a")?; + if g.u64_string("generation")? != GENERATION { + return Err(WireError("unsupported artifact generation".into())); + } + serial_field(&mut g, "ownerId", "own")?; + crate::wire::Location::from_json(g.value("writeLocation")?)?; + g.finish()?; + } + Ok(()) +} + fn owner_guard(conn: &Weak, id: String, delivery: bool) -> Option> { Some(Arc::new(OwnerGuard { id, @@ -704,6 +742,36 @@ fn complete( value, extra: Extra::None, }), + (Hook::Writers, Ok(value)) => { + // Every granted writer gets its guard here, inside the reactor, so a caller that + // abandoned the reply still releases them. + let mut grants = Vec::new(); + let mut closed = false; + if let Some(Value::Array(list)) = value.get("writers") { + for w in list { + let mut g = Fields::new(w, "writer")?; + let name = g.id("name")?; + let artifact_id = g.id("artifactId")?; + let owner_id = g.id("ownerId")?; + let location = crate::wire::Location::from_json(g.value("writeLocation")?)?; + match owner_guard(conn, owner_id, false) { + Some(owner) => grants.push(WriterGrant { name, artifact_id, owner, location }), + None => { + closed = true; + break; + } + } + } + } + if closed { + Err(BusError::lost("client closed")) + } else { + Ok(Reply { + value, + extra: Extra::Writers(grants), + }) + } + } (Hook::Owner, Ok(value)) => { let id = Fields::of(&value, "reply").id("ownerId")?; match owner_guard(conn, id, false) { @@ -826,12 +894,22 @@ fn u64_field(f: &mut Fields<'_>, key: &'static str) -> Result { parse_u64(s).ok_or_else(|| WireError(format!("{key} is not a U64"))) } +/// Moves an object field out of a validated body (BUS-02: the payload is the one large part of a +/// delivery, and it used to be deep-copied out of the tree it was parsed into). +fn take_object(body: &mut Map, key: &str) -> Map { + match body.remove(key) { + Some(Value::Object(m)) => m, + _ => Map::new(), + } +} + fn on_delivery( shared: &Arc, conn: &Weak, - env: Envelope, + mut env: Envelope, ) -> Result<(), WireError> { - let mut f = Fields::of(&env.body, "delivery"); + let mut body = std::mem::take(&mut env.body); + let mut f = Fields::of(&body, "delivery"); let delivery_id = f.id("deliveryId")?; let delivery_serial = parse_serial_id("dlv", &delivery_id) .filter(|n| *n > 0) @@ -854,14 +932,16 @@ fn on_delivery( return Err(WireError("service incarnation is not svc-".into())); } let method = f.method("method")?; - let payload = f.object("payload")?.clone(); + f.object("payload")?; f.finish()?; + let payload = take_object(&mut body, "payload"); accept_delivery_serial(shared, delivery_serial)?; let req = Request { reply_guard: Arc::new(ReplyGuard { conn: guard.conn.clone(), call_id: call_id.clone(), request_delivery_id: delivery_id.clone(), + replied: std::sync::atomic::AtomicBool::new(false), }), guard, call_id, @@ -891,8 +971,9 @@ fn on_delivery( if parse_serial_id("svc", &service_incarnation).is_none() { return Err(WireError("service incarnation is not svc-".into())); } - let outcome = f.object("outcome")?.clone(); + f.object("outcome")?; f.finish()?; + let outcome = take_object(&mut body, "outcome"); accept_delivery_serial(shared, delivery_serial)?; let res = RpcResult { guard, @@ -923,8 +1004,9 @@ fn on_delivery( } let topic_sequence = u64_field(&mut f, "topicSequence")?; let replaced = u64_field(&mut f, "replaced")?; - let payload = f.object("payload")?.clone(); + f.object("payload")?; f.finish()?; + let payload = take_object(&mut body, "payload"); accept_delivery_serial(shared, delivery_serial)?; let msg = Message { guard, diff --git a/services/flysim/crates/flybus/src/lib.rs b/services/flysim/crates/flybus/src/lib.rs index fc19bc1..b5627fb 100644 --- a/services/flysim/crates/flybus/src/lib.rs +++ b/services/flysim/crates/flybus/src/lib.rs @@ -26,7 +26,7 @@ mod transport; pub use client::{ Artifact, ArtifactFile, ArtifactWriter, Artifacts, CancelState, Client, ClientConfig, IN_MEMORY_STORE_ID, Message, - Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, Service, + Mode, PendingCall, PublishReceipt, Request, Responder, Retained, RpcResult, SealedReply, Service, Unsealed, ServiceConfig, SessionInfo, Subscription, SubscriptionConfig, TopicInfo, }; pub use error::{BusError, Dispatch, ErrorCode}; diff --git a/services/flysim/crates/flybus/src/router/mod.rs b/services/flysim/crates/flybus/src/router/mod.rs index 66cb959..aea8e7f 100644 --- a/services/flysim/crates/flybus/src/router/mod.rs +++ b/services/flysim/crates/flybus/src/router/mod.rs @@ -331,6 +331,47 @@ async fn read_loop( }; inner.with_state(|s| s.finish_allocate(job, created)); } + Outcome::SealThenAdmit(job) => { + // The writers a sending command attaches are sealed before it is admitted + // (bus-v1 section 12 amendment 2026-10-02): the copies run here, outside the + // state lock, and this connection's next command waits for the admission, so + // its commands stay in order. A recycled writer's staging file is kept and + // renamed for the artifact it becomes; otherwise it goes with the copy. + let total: u64 = job.seals.iter().map(|s| s.len).sum(); + let plan: Vec<(u64, u64, Option)> = + job.seals.iter().map(|s| (s.serial, s.len, s.recycle)).collect(); + let i = inner.clone(); + let run = move || { + plan.into_iter() + .map(|(serial, len, recycle)| { + let r = i.store.seal_prefix(serial, len); + match recycle { + Some(next) if r.is_ok() => i + .store + .rename(&crate::store::staging_rel(serial), &crate::store::staging_rel(next)) + .map_err(crate::store::SealFailure::Io), + _ => { + i.store.remove(&crate::store::staging_rel(serial)); + r + } + } + }) + .collect::>() + }; + let results = if total <= crate::store::INLINE_IO_BYTES { + run() + } else { + let n = job.seals.len(); + tokio::task::spawn_blocking(run).await.unwrap_or_else(|e| { + (0..n) + .map(|_| Err(SealFailure::Io(io::Error::other(e.to_string())))) + .collect() + }) + }; + if let Outcome::Close = inner.with_state(|s| s.finish_sealing_send(job, results)) { + return; + } + } Outcome::Seal(job) if job.len <= crate::store::INLINE_IO_BYTES => { // A small seal copies in place, for the same reason; the connection's reader // waits for it as it waits for any command (BUS-01). The outcome is the diff --git a/services/flysim/crates/flybus/src/router/state.rs b/services/flysim/crates/flybus/src/router/state.rs index 2542d8b..ffb995d 100644 --- a/services/flysim/crates/flybus/src/router/state.rs +++ b/services/flysim/crates/flybus/src/router/state.rs @@ -15,6 +15,8 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; +use serde::Serialize; +use serde_json::value::RawValue; use serde_json::{Map, Value}; use tokio::sync::{Notify, watch}; @@ -24,7 +26,8 @@ use crate::policy::{Grants, Policy}; use crate::store::{sealed_rel, staging_rel}; use crate::wire::{ ArtifactRef, Attachment, Envelope, Fields, GENERATION, Identity, Kind, MAJOR, MAX_BATCH, - MAX_CREDIT, MAX_ENVELOPE_BYTES, MINOR, WireError, id_batch, parse_serial_id, serial_id, + MAX_CREDIT, MAX_ENVELOPE_BYTES, MINOR, Unnumbered, WireError, id_batch, parse_serial_id, + serial_id, }; pub(crate) type ConnKey = u64; @@ -155,6 +158,9 @@ pub(crate) enum Outcome { Allocate(AllocJob), /// Copy staging into the sealed file (off the routing path), then call `finish_seal`. Seal(SealJob), + /// Seal the writers a sending command attaches (off the routing path), then call + /// `finish_sealing_send`, which admits the command (BUS-02). + SealThenAdmit(SealingSend), /// The connection was closed; stop reading. Close, } @@ -176,18 +182,36 @@ pub(crate) struct SealJob { pub owner: u64, } +/// One writer a sending command attaches, sealed as the command is admitted (bus-v1 section 12 +/// amendment 2026-10-02). +pub(crate) struct SendSeal { + /// The writer's artifact. + pub serial: u64, + /// The length sealed: the attachment's `byteLength`, at most the allocation. + pub len: u64, + /// The staging allocation. + pub capacity: u64, + pub owner: u64, + /// With `recycle`, the artifact the staging file is reissued as, once sealed. + pub recycle: Option, +} + +pub(crate) struct SealingSend { + pub conn: ConnKey, + pub env: Envelope, + pub seals: Vec, +} + pub(crate) enum NextFrame { Frame(Vec), Idle, Gone, } +/// A router frame, encoded once when it is built (BUS-02); its envelope id is spliced in when the +/// scheduler selects it. pub(crate) struct Outbound { - kind: Kind, - op: String, - reply_to: Option, - body: Map, - attachments: Vec, + frame: Unnumbered, /// Conservative encoded size using the longest router envelope id. bytes: usize, } @@ -324,7 +348,7 @@ struct TopicMsg { topic: String, topic_incarnation: String, sequence: u64, - payload: Map, + payload: Box, attachments: Vec<(String, ArtifactRef)>, artifacts: Vec, bytes: usize, @@ -361,7 +385,7 @@ struct Svc { struct ResultMsg { responder: Identity, - outcome: Map, + outcome: Box, attachments: Vec<(String, ArtifactRef)>, artifacts: Vec, } @@ -386,7 +410,8 @@ struct Call { service_incarnation: String, service_conn: ConnKey, method: String, - payload: Map, + /// The validated payload, encoded once at admission and forwarded verbatim (BUS-02). + payload: Box, attachments: Vec<(String, ArtifactRef)>, artifacts: Vec, phase: Phase, @@ -461,10 +486,10 @@ fn attachments_with_owner(list: &[(String, ArtifactRef)], owner: &str) -> Vec( kind: Kind, op: &str, - body: Map, + body: B, attachments: Vec, ) -> usize { let id = serial_id("bus", MAX_SERIAL); @@ -482,47 +507,113 @@ fn frame_len( .unwrap_or(usize::MAX) } +/// An identity as delivery bodies carry it ([`Identity::to_json`]'s members, in order). +#[derive(Serialize)] +struct IdentityBody<'a> { + #[serde(rename = "clientId")] + client_id: &'a str, + #[serde(rename = "clientIncarnation")] + client_incarnation: &'a str, +} + +impl<'a> From<&'a Identity> for IdentityBody<'a> { + fn from(i: &'a Identity) -> IdentityBody<'a> { + IdentityBody { client_id: &i.client_id, client_incarnation: &i.client_incarnation } + } +} + +/// `rpc.request` (bus-v1 section 5), members in the order the router always sent them; the +/// payload is the admitted bytes, not a copy of a parsed tree (BUS-02). +#[derive(Serialize)] +struct RequestBody<'a> { + #[serde(rename = "deliveryId")] + delivery_id: &'a str, + #[serde(rename = "callId")] + call_id: &'a str, + caller: IdentityBody<'a>, + target: &'a str, + #[serde(rename = "serviceIncarnation")] + service_incarnation: &'a str, + method: &'a str, + payload: &'a RawValue, +} + +/// `rpc.result`. +#[derive(Serialize)] +struct ResultBody<'a> { + #[serde(rename = "deliveryId")] + delivery_id: &'a str, + #[serde(rename = "callId")] + call_id: &'a str, + responder: IdentityBody<'a>, + #[serde(rename = "serviceIncarnation")] + service_incarnation: &'a str, + outcome: &'a RawValue, +} + +/// `topic.message`. +#[derive(Serialize)] +struct TopicBody<'a> { + #[serde(rename = "deliveryId")] + delivery_id: &'a str, + #[serde(rename = "subscriptionId")] + subscription_id: &'a str, + topic: &'a str, + #[serde(rename = "topicIncarnation")] + topic_incarnation: &'a str, + #[serde(rename = "topicSequence")] + topic_sequence: String, + replaced: String, + payload: &'a RawValue, +} + +/// Encodes an admitted payload once (BUS-02). It was parsed strictly on the way in, so it +/// re-encodes; a failure here is the caller's refusal like any oversized envelope. +fn raw(value: &Map) -> Result, BusError> { + serde_json::value::to_raw_value(value) + .map_err(|e| BusError::new(ErrorCode::InvalidEnvelope, format!("payload: {e}"))) +} + impl Call { - fn request_body(&self, delivery_id: &str) -> Map { - obj(vec![ - ("deliveryId", delivery_id.into()), - ("callId", self.call_id.clone().into()), - ("caller", self.caller_identity.to_json()), - ("target", self.target.clone().into()), - ( - "serviceIncarnation", - self.service_incarnation.clone().into(), - ), - ("method", self.method.clone().into()), - ("payload", Value::Object(self.payload.clone())), - ]) + fn request_body<'a>(&'a self, delivery_id: &'a str) -> RequestBody<'a> { + RequestBody { + delivery_id, + call_id: &self.call_id, + caller: (&self.caller_identity).into(), + target: &self.target, + service_incarnation: &self.service_incarnation, + method: &self.method, + payload: &self.payload, + } } - fn result_body(&self, delivery_id: &str, result: &ResultMsg) -> Map { - obj(vec![ - ("deliveryId", delivery_id.into()), - ("callId", self.call_id.clone().into()), - ("responder", result.responder.to_json()), - ( - "serviceIncarnation", - self.service_incarnation.clone().into(), - ), - ("outcome", Value::Object(result.outcome.clone())), - ]) + fn result_body<'a>(&'a self, delivery_id: &'a str, result: &'a ResultMsg) -> ResultBody<'a> { + ResultBody { + delivery_id, + call_id: &self.call_id, + responder: (&result.responder).into(), + service_incarnation: &self.service_incarnation, + outcome: &result.outcome, + } } } impl TopicMsg { - fn body(&self, delivery_id: &str, subscription_id: &str, replaced: u64) -> Map { - obj(vec![ - ("deliveryId", delivery_id.into()), - ("subscriptionId", subscription_id.into()), - ("topic", self.topic.clone().into()), - ("topicIncarnation", self.topic_incarnation.clone().into()), - ("topicSequence", self.sequence.to_string().into()), - ("replaced", replaced.to_string().into()), - ("payload", Value::Object(self.payload.clone())), - ]) + fn body<'a>( + &'a self, + delivery_id: &'a str, + subscription_id: &'a str, + replaced: u64, + ) -> TopicBody<'a> { + TopicBody { + delivery_id, + subscription_id, + topic: &self.topic, + topic_incarnation: &self.topic_incarnation, + topic_sequence: self.sequence.to_string(), + replaced: replaced.to_string(), + payload: &self.payload, + } } } @@ -651,41 +742,34 @@ impl State { } /// Builds a router-originated item without assigning its envelope id. IDs are assigned only - /// after the scheduler selects an item, so fairness cannot reorder numbered envelopes. - fn outbound( + /// after the scheduler selects an item, so fairness cannot reorder numbered envelopes. The + /// item is encoded here, once (BUS-02), with the id left to splice in. + fn outbound( &self, kind: Kind, op: &str, reply_to: Option, - body: Map, + body: B, attachments: Vec, ) -> Option { - let mut env = Envelope::new(serial_id("bus", MAX_SERIAL), kind, op, body.clone()); - env.reply_to = reply_to; - env.attachments = attachments.clone(); - let bytes = env.encode().ok()?.len(); - Some(Outbound { + let head = crate::wire::EnvelopeHead { + major: MAJOR, + minor: MINOR, + id: "", + reply_to: reply_to.as_deref(), kind, - op: op.to_owned(), - reply_to: env.reply_to, - body, - attachments, - bytes, - }) + op, + }; + let max_id = serial_id("bus", MAX_SERIAL).len(); + let frame = Unnumbered::encode(&head, &body, &attachments, max_id).ok()?; + let bytes = frame.len() + max_id; + Some(Outbound { frame, bytes }) } fn encode_outbound(&mut self, c: ConnKey, item: Outbound) -> Option> { let conn = self.conns.get_mut(&c)?; conn.out_serial += 1; - let mut env = Envelope::new( - serial_id("bus", conn.out_serial), - item.kind, - &item.op, - item.body, - ); - env.reply_to = item.reply_to; - env.attachments = item.attachments; - env.encode().ok() + Some(item.frame.number(&serial_id("bus", conn.out_serial))) } /// Queues a reply or notice on the control lane; closes the connection if the lane is full. @@ -1114,7 +1198,7 @@ impl State { // ----------------------------------------------------------------------------------------- // Commands - pub(crate) fn handle(&mut self, c: ConnKey, env: Envelope) -> Outcome { + pub(crate) fn handle(&mut self, c: ConnKey, mut env: Envelope) -> Outcome { let Some(conn) = self.conns.get_mut(&c) else { return Outcome::Close; }; @@ -1144,6 +1228,34 @@ impl State { ); } let op = env.op.clone(); + if matches!(op.as_str(), "rpc.call" | "rpc.reply" | "publish") { + match self.sealing_attachments(c, &mut env) { + Ok(None) => {} + Ok(Some(seals)) => { + return Outcome::SealThenAdmit(SealingSend { conn: c, env, seals }); + } + Err(e) => { + // Refused before anything was sealed: the writers it named are released + // all the same, as a refused sealing send releases them (bus-v1 section 12, + // amendment 2026-10-02). + for a in &env.attachments { + let Some(owner) = parse_serial_id("own", &a.owner_id) else { + continue; + }; + if matches!( + self.conns[&c].owners.get(&OwnerKey::Hold(owner)), + Some(Owner::Writer { sealing: false, .. }) + ) && let Some(w) = self.take_owner(c, OwnerKey::Hold(owner)) + { + self.release_owner(c, w); + } + } + self.reply(c, &env.id, &op, Err(e)); + self.flush_notices(); + return if self.conns.contains_key(&c) { Outcome::Done } else { Outcome::Close }; + } + } + } let result = if !env.attachments.is_empty() && !matches!(op.as_str(), "rpc.call" | "rpc.reply" | "publish") { @@ -1192,6 +1304,233 @@ impl State { } } + // ----------------------------------------------------------------------------------------- + // Sealing on send (bus-v1 section 12 amendment 2026-10-02, BUS-02) + + /// Finds the attachments of a sending command that name one of the sender's own writers + /// rather than a sealed artifact, validates each as `artifact.seal` would, and marks them + /// sealing. `None` when there are none (the command takes the ordinary path). Takes the + /// body's `recycle` member, which only such a command may carry. + fn sealing_attachments( + &mut self, + c: ConnKey, + env: &mut Envelope, + ) -> Result>, BusError> { + let recycle = match env.body.remove("recycle") { + None => false, + Some(Value::Bool(b)) => b, + Some(_) => return err(ErrorCode::InvalidEnvelope, "recycle must be a boolean"), + }; + let mut found: Vec<(u64, u64, u64)> = Vec::new(); + for a in &env.attachments { + let Some(owner) = parse_serial_id("own", &a.owner_id) else { + continue; + }; + let Some(Owner::Writer { artifact, sealing }) = + self.conns[&c].owners.get(&OwnerKey::Hold(owner)) + else { + continue; + }; + let (artifact, sealing) = (*artifact, *sealing); + if parse_serial_id("a", &a.reference.artifact_id) != Some(artifact) { + // Another artifact under a writer's owner id: check_owned refuses it later. + continue; + } + if sealing || found.iter().any(|(s, _, _)| *s == artifact) { + return err(ErrorCode::OwnerInvalid, "a seal is already in progress"); + } + let art = &self.artifacts[&artifact]; + let r = &a.reference; + if r.store_id != self.store_id + || r.generation != GENERATION + || r.content_type != art.content_type + || r.digest.is_some() + || r.byte_length > art.byte_length + { + return err( + ErrorCode::ArtifactMismatch, + format!( + "attachment {:?} does not describe its writer: same store, generation and \ +content type, a null digest and at most the allocated length", + a.name + ), + ); + } + found.push((artifact, owner, r.byte_length)); + } + if found.is_empty() { + if recycle { + return err(ErrorCode::InvalidEnvelope, "recycle without a writer attached"); + } + return Ok(None); + } + let sealed: u64 = found.iter().map(|(_, _, len)| len).sum(); + if self.store_bytes.saturating_add(sealed) > self.limits.max_store_bytes { + return err(ErrorCode::QuotaExceeded, "no room for the sealing copies"); + } + self.store_bytes += sealed; + let mut seals = Vec::with_capacity(found.len()); + for (serial, owner, len) in found { + let art = self.artifacts.get_mut(&serial).expect("a writer's artifact is registered"); + art.state = ArtState::Sealing; + let capacity = art.byte_length; + self.conns.get_mut(&c).expect("present").owners.insert( + OwnerKey::Hold(owner), + Owner::Writer { artifact: serial, sealing: true }, + ); + let recycle = recycle.then(|| { + self.next_artifact += 1; + self.next_artifact + }); + seals.push(SendSeal { serial, len, capacity, owner, recycle }); + } + Ok(Some(seals)) + } + + /// Completes a sealing send: every copy has been made (`results`, in `job.seals` order) and, + /// for a recycled writer, its staging file moved to the new artifact's name. Then the + /// command is admitted exactly as an ordinary one whose attachments the sender had sealed + /// first; a refused command releases what it sealed, as a sender dropping its holds would. + pub(crate) fn finish_sealing_send( + &mut self, + job: SealingSend, + results: Vec>, + ) -> Outcome { + let SealingSend { conn: c, env, seals } = job; + let live = |s: &State, seal: &SendSeal| { + s.conns.get(&c).is_some_and(|conn| { + matches!(conn.owners.get(&OwnerKey::Hold(seal.owner)), + Some(Owner::Writer { artifact, sealing: true }) if *artifact == seal.serial) + }) + }; + let all_live = seals.iter().all(|seal| live(self, seal)); + let failure = results.iter().find_map(|r| r.as_ref().err()).map(|e| match e { + crate::store::SealFailure::Mismatch(m) => BusError::new(ErrorCode::ArtifactMismatch, m.clone()), + crate::store::SealFailure::Io(e) => { + BusError::new(ErrorCode::StoreFailure, format!("seal: {e}")) + } + }); + if failure.is_some() || !all_live { + // Nothing is admitted: every writer named is released and every copy unlinked. + for seal in &seals { + if self.artifacts.remove(&seal.serial).is_some() { + self.store_bytes -= seal.len + seal.capacity; + } + self.unlinks.push(sealed_rel(seal.serial)); + self.unlinks.push(staging_rel(seal.recycle.unwrap_or(seal.serial))); + if live(self, seal) { + self.take_owner(c, OwnerKey::Hold(seal.owner)); + } + } + if !self.conns.contains_key(&c) { + return Outcome::Close; + } + let e = failure + .unwrap_or_else(|| BusError::new(ErrorCode::ArtifactGone, "the writer was released during the seal")); + self.reply(c, &env.id, &env.op, Err(e)); + self.flush_notices(); + return if self.conns.contains_key(&c) { Outcome::Done } else { Outcome::Close }; + } + // Sealed: each writer's owner becomes the sender's hold, as after `artifact.seal`. + let mut writers = Vec::new(); + for seal in &seals { + let art = self.artifacts.get_mut(&seal.serial).expect("sealing artifact is registered"); + art.state = ArtState::Sealed; + art.byte_length = seal.len; + art.digest = None; + art.roots = 1; + let content_type = art.content_type.clone(); + self.conns.get_mut(&c).expect("present").owners.insert( + OwnerKey::Hold(seal.owner), + Owner::Hold { artifact: seal.serial }, + ); + match seal.recycle { + // The staging file goes on as a new writer of the same allocation. + Some(next) if self.ordinary_budget_left(c) => { + self.artifacts.insert( + next, + Art { + state: ArtState::Writing, + byte_length: seal.capacity, + content_type, + digest: None, + roots: 0, + }, + ); + let conn = self.conns.get_mut(&c).expect("present"); + conn.hold_issued += 1; + let owner = conn.hold_issued; + self.insert_owner( + c, + OwnerKey::Hold(owner), + Owner::Writer { artifact: next, sealing: false }, + ); + writers.push((seal.serial, next, owner)); + } + Some(next) => { + self.store_bytes -= seal.capacity; + self.unlinks.push(staging_rel(next)); + } + // The staging file was unlinked with the copy; its reservation ends here. + None => self.store_bytes -= seal.capacity, + } + } + let op = env.op.clone(); + let result = match op.as_str() { + "rpc.call" => self.op_call(c, &env), + "rpc.reply" => self.op_reply(c, &env), + "publish" => self.op_publish(c, &env), + _ => unreachable!("only sending commands seal"), + }; + let result = match result { + Ok(mut value) => { + if !writers.is_empty() { + let list = writers + .iter() + .map(|(sealed, next, owner)| { + let name = env + .attachments + .iter() + .find(|a| parse_serial_id("a", &a.reference.artifact_id) == Some(*sealed)) + .map(|a| a.name.clone()) + .unwrap_or_default(); + let loc = crate::wire::Location { + store_id: self.store_id.clone(), + relative_path: staging_rel(*next), + }; + Value::Object(obj(vec![ + ("name", name.into()), + ("artifactId", serial_id("a", *next).into()), + ("generation", GENERATION.to_string().into()), + ("ownerId", serial_id("own", *owner).into()), + ("writeLocation", loc.to_json()), + ])) + }) + .collect(); + value.insert("writers".into(), Value::Array(list)); + } + Ok(value) + } + Err(e) => { + // Refused: the holds the seals made and the recycled writers go with it. + for seal in &seals { + if let Some(owner) = self.take_owner(c, OwnerKey::Hold(seal.owner)) { + self.release_owner(c, owner); + } + } + for (_, _, owner) in &writers { + if let Some(owner) = self.take_owner(c, OwnerKey::Hold(*owner)) { + self.release_owner(c, owner); + } + } + Err(e) + } + }; + self.reply(c, &env.id, &op, result); + self.flush_notices(); + if self.conns.contains_key(&c) { Outcome::Done } else { Outcome::Close } + } + fn grants(&self, c: ConnKey) -> &Grants { &self.conns[&c].hello.as_ref().expect("after hello").grants } @@ -1490,7 +1829,7 @@ impl State { let target = f.name("target").map_err(wire)?; let expected = f.nullable_id("expectedIncarnation").map_err(wire)?; let method = f.method("method").map_err(wire)?; - let payload = f.object("payload").map_err(wire)?.clone(); + let payload = raw(f.object("payload").map_err(wire)?)?; f.finish().map_err(wire)?; let Some(call_serial) = parse_serial_id("call", &call_id) else { return err(ErrorCode::InvalidEnvelope, "callId must be call-"); @@ -1584,7 +1923,7 @@ impl State { let mut f = Fields::of(&env.body, "rpc.reply"); let call_id = f.id("callId").map_err(wire)?; let delivery_id = f.id("requestDeliveryId").map_err(wire)?; - let outcome = f.object("outcome").map_err(wire)?.clone(); + let outcome = raw(f.object("outcome").map_err(wire)?)?; f.finish().map_err(wire)?; let Some(n) = parse_serial_id("dlv", &delivery_id) else { return err( @@ -2022,7 +2361,7 @@ impl State { fn op_publish(&mut self, c: ConnKey, env: &Envelope) -> Result, BusError> { let mut f = Fields::of(&env.body, "publish"); let topic = f.name("topic").map_err(wire)?; - let payload = f.object("payload").map_err(wire)?.clone(); + let payload = raw(f.object("payload").map_err(wire)?)?; f.finish().map_err(wire)?; if !Grants::allows(&self.grants(c).publish, &topic) { return err( @@ -2548,6 +2887,7 @@ impl State { let call = &self.calls[&key]; let body = call.result_body(&did, &msg); let atts = attachments_with_owner(&msg.attachments, &did); + let frame = self.outbound(Kind::Delivery, "rpc.result", None, body, atts); self.insert_owner( c, OwnerKey::Delivery(n), @@ -2556,7 +2896,7 @@ impl State { kind: DeliveryKind::Result { call: key }, }, ); - return self.outbound(Kind::Delivery, "rpc.result", None, body, atts); + return frame; } // Requests for services this connection registered, round robin. let conn = &self.conns[&c]; @@ -2583,13 +2923,16 @@ impl State { conn.requests.insert(n, key); conn.reply_capabilities += 1; let call = self.calls.get_mut(&key).expect("queued call is registered"); - // Dispatched before a byte of it is written. + // Dispatched before a byte of it is written. (The frame is built below, under the + // same lock, before anything can write it.) call.phase = Phase::Dispatched { delivery: n }; call.reply_capability = true; let did = serial_id("dlv", n); + let call = &self.calls[&key]; let body = call.request_body(&did); let atts = attachments_with_owner(&call.attachments, &did); let artifacts = call.artifacts.clone(); + let frame = self.outbound(Kind::Delivery, "rpc.request", None, body, atts); self.insert_owner( c, OwnerKey::Delivery(n), @@ -2602,7 +2945,7 @@ impl State { }, }, ); - return self.outbound(Kind::Delivery, "rpc.request", None, body, atts); + return frame; } None } @@ -2630,8 +2973,10 @@ impl State { conn.delivery_issued += 1; let n = conn.delivery_issued; let did = serial_id("dlv", n); - let body = msg.body(&did, &serial_id("sub", id), replaced); + let sid = serial_id("sub", id); + let body = msg.body(&did, &sid, replaced); let atts = attachments_with_owner(&msg.attachments, &did); + let frame = self.outbound(Kind::Delivery, "topic.message", None, body, atts); self.insert_owner( c, OwnerKey::Delivery(n), @@ -2640,7 +2985,7 @@ impl State { kind: DeliveryKind::Topic { sub: id }, }, ); - return self.outbound(Kind::Delivery, "topic.message", None, body, atts); + return frame; } None } diff --git a/services/flysim/crates/flybus/src/store.rs b/services/flysim/crates/flybus/src/store.rs index ed975e3..9e518f3 100644 --- a/services/flysim/crates/flybus/src/store.rs +++ b/services/flysim/crates/flybus/src/store.rs @@ -159,6 +159,36 @@ impl Store { result } + /// Copies the first `len` staging bytes into a fresh sealed file (BUS-02: a writer attached + /// to a sending command seals the bytes its attachment declares, at most its allocation). + /// The staging file is left for the caller. + pub(crate) fn seal_prefix(&self, serial: u64, len: u64) -> Result<(), SealFailure> { + let mut src = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(self.path(&staging_rel(serial)))?; + let dst_path = self.path(&sealed_rel(serial)); + let mut dst = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW) + .open(&dst_path)?; + let result = copy_prefix(&mut src, &mut dst, len).and_then(|()| { + dst.set_permissions(fs::Permissions::from_mode(0o444))?; + Ok(()) + }); + if result.is_err() { + let _ = fs::remove_file(&dst_path); + } + result + } + + /// Renames a store file within the store (a recycled writer's staging file). + pub(crate) fn rename(&self, from: &str, to: &str) -> io::Result<()> { + fs::rename(self.path(from), self.path(to)) + } + /// Unlinks a store file; a missing file is not an error. pub(crate) fn remove(&self, rel: &str) { let _ = fs::remove_file(self.path(rel)); @@ -187,7 +217,9 @@ fn copy_exact( digest: Option<&str>, ) -> Result<(), SealFailure> { let mut hasher = digest.map(|_| Sha256::new()); - let mut buf = vec![0u8; 256 * 1024]; + // Sized to the copy (BUS-02): a fixed 256 KiB buffer is a fresh mapping, and its page + // faults, on every seal of a frame-sized artifact. + let mut buf = vec![0u8; (len.saturating_add(1)).clamp(1, 256 * 1024) as usize]; let mut remaining = len; while remaining > 0 { let want = remaining.min(buf.len() as u64) as usize; @@ -220,6 +252,68 @@ fn copy_exact( Ok(()) } +fn copy_prefix(src: &mut File, dst: &mut File, len: u64) -> Result<(), SealFailure> { + // In the kernel where it can (`copy_file_range`: one copy, no bounce through a user buffer; + // on the store's tmpfs that halves a frame's seal), else through a buffer. + let mut done: u64 = 0; + while done < len { + let want = (len - done).min(1 << 30) as usize; + // SAFETY: two valid descriptors; null offsets use and advance each file's position. + let n = unsafe { + libc::copy_file_range( + src.as_raw_fd(), + std::ptr::null_mut(), + dst.as_raw_fd(), + std::ptr::null_mut(), + want, + 0, + ) + }; + if n < 0 { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::Interrupted { + continue; + } + if done == 0 + && matches!( + e.raw_os_error(), + Some(libc::ENOSYS | libc::EXDEV | libc::EINVAL | libc::EOPNOTSUPP) + ) + { + return copy_prefix_buffered(src, dst, len); + } + return Err(SealFailure::Io(e)); + } + if n == 0 { + return Err(SealFailure::Mismatch(format!( + "staging holds {done} of {len} declared bytes" + ))); + } + done += n as u64; + } + Ok(()) +} + +fn copy_prefix_buffered(src: &mut File, dst: &mut File, len: u64) -> Result<(), SealFailure> { + // Sized to the copy: a frame or a memory image is one read and one write, and the buffer is + // small enough to come from the heap rather than a fresh mapping each time. + let mut buf = vec![0u8; len.clamp(1, 256 * 1024) as usize]; + let mut remaining = len; + while remaining > 0 { + let want = remaining.min(buf.len() as u64) as usize; + let n = read_retry(src, &mut buf[..want])?; + if n == 0 { + return Err(SealFailure::Mismatch(format!( + "staging holds {} of {len} declared bytes", + len - remaining + ))); + } + dst.write_all(&buf[..n])?; + remaining -= n as u64; + } + Ok(()) +} + /// Deletes store directories under `root` that carry the marker and whose lock is free. /// Directories without the marker are never touched. fn clean_orphans(root: &Path) -> io::Result<()> { @@ -280,18 +374,63 @@ pub(crate) fn resolve(root: &Path, store_id: &str, loc: &Location) -> Result return Err(refuse("parent, root or current-directory component")), } } - let base = root.join(&loc.store_id); - let base = base - .canonicalize() + // The directory part (`sealed`, `staging`) is resolved once per store directory and cached + // (BUS-02): canonicalizing the whole path is a readlink per component, twice, on every open + // of every artifact. The file itself is then checked with one lstat: a symlink there is + // refused like one that escapes (the open that follows uses O_NOFOLLOW as well). + let (dir, file) = match loc.relative_path.rsplit_once('/') { + Some((dir, file)) => (Some(dir), file), + None => (None, loc.relative_path.as_str()), + }; + let base = canonical_dir(&root.join(&loc.store_id), None) .map_err(|e| refuse(&format!("store directory: {e}")))?; - let full = base.join(rel).canonicalize().map_err(|e| match e.kind() { - io::ErrorKind::NotFound => BusError::new(ErrorCode::ArtifactGone, "artifact file is gone"), - _ => refuse(&e.to_string()), - })?; - if !full.starts_with(&base) { + let parent = match dir { + None => base.clone(), + Some(dir) => canonical_dir(&root.join(&loc.store_id), Some(dir)).map_err(|e| match e.kind() { + io::ErrorKind::NotFound => BusError::new(ErrorCode::ArtifactGone, "artifact file is gone"), + _ => refuse(&e.to_string()), + })?, + }; + if !parent.starts_with(&base) { return Err(refuse("escapes the store")); } - Ok(full) + let full = parent.join(file); + match fs::symlink_metadata(&full) { + Ok(m) if m.file_type().is_symlink() => Err(refuse("escapes the store")), + Ok(_) => Ok(full), + Err(e) if e.kind() == io::ErrorKind::NotFound => { + Err(BusError::new(ErrorCode::ArtifactGone, "artifact file is gone")) + } + Err(e) => Err(refuse(&e.to_string())), + } +} + +/// `store.join(dir).canonicalize()`, cached per process: a store's directories are made by its +/// router when the store is created and never move. +fn canonical_dir(store: &Path, dir: Option<&str>) -> io::Result { + use std::collections::HashMap; + use std::sync::Mutex; + static CACHE: Mutex>> = Mutex::new(None); + let key = match dir { + Some(dir) => store.join(dir), + None => store.to_path_buf(), + }; + if let Some(hit) = CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .and_then(|m| m.get(&key).cloned()) + { + return Ok(hit); + } + let resolved = key.canonicalize()?; + let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner()); + let map = cache.get_or_insert_with(HashMap::new); + if map.len() > 256 { + map.clear(); + } + map.insert(key, resolved.clone()); + Ok(resolved) } pub(crate) fn open_read(path: &Path) -> io::Result { diff --git a/services/flysim/crates/flybus/src/wire.rs b/services/flysim/crates/flybus/src/wire.rs index 6486b74..758d236 100644 --- a/services/flysim/crates/flybus/src/wire.rs +++ b/services/flysim/crates/flybus/src/wire.rs @@ -37,6 +37,8 @@ pub const CONTRACT: &str = "flybus 1.0 frame: u32le length, 1..=65536 bytes of strict UTF-8 JSON envelope: protocol major minor id replyTo kind op body attachments attachment: name ref ownerId [readLocation(storeId relativePath): in a router delivery only] +sealing attachment: in rpc.call rpc.reply publish, ownerId may be the sender's own unsealed writer of ref.artifactId; ref.byteLength <= its allocation, digest null; the router seals that prefix on admission and the writer becomes the sender's hold +recycle: optional boolean member of an rpc.call rpc.reply publish body with a sealing attachment; the reply value then carries writers[name artifactId generation ownerId writeLocation], each sealed writer's staging allocation reissued ref: storeId artifactId generation byteLength contentType digest reply: ok value | ok error{code message dispatch} bus.hello: clientId clientIncarnation supportedMajors -> routerId connectionId selectedMajor selectedMinor contractDigest limits @@ -257,11 +259,16 @@ impl<'de> Visitor<'de> for StrictVisitor { fn visit_map>(self, mut map: A) -> Result { let mut out = Map::new(); while let Some(key) = map.next_key::()? { - if out.contains_key(&key) { - return Err(de::Error::custom(format!("duplicate key {key:?}"))); - } let v = map.next_value_seed(StrictSeed)?; - out.insert(key, v); + // One hash per key (BUS-02). + match out.entry(key) { + serde_json::map::Entry::Vacant(slot) => { + slot.insert(v); + } + serde_json::map::Entry::Occupied(slot) => { + return Err(de::Error::custom(format!("duplicate key {:?}", slot.key()))); + } + } } Ok(Value::Object(out)) } @@ -273,7 +280,8 @@ impl<'de> Visitor<'de> for StrictVisitor { /// Reads the fields of one JSON object, then refuses any it did not read. pub struct Fields<'a> { map: &'a Map, - seen: HashSet<&'static str>, + // A handful of keys per object: a vector beats hashing them (BUS-02). + seen: Vec<&'static str>, what: &'static str, } @@ -288,19 +296,19 @@ impl<'a> Fields<'a> { pub fn of(map: &'a Map, what: &'static str) -> Fields<'a> { Fields { map, - seen: HashSet::new(), + seen: Vec::with_capacity(8), what, } } /// A field that may be absent; read (so [`Fields::finish`] accepts it) when present. pub fn optional(&mut self, key: &'static str) -> Option<&'a Value> { - self.seen.insert(key); + self.seen.push(key); self.map.get(key) } pub fn value(&mut self, key: &'static str) -> Result<&'a Value, WireError> { - self.seen.insert(key); + self.seen.push(key); match self.map.get(key) { Some(v) => Ok(v), None => err(format!("{}: missing field {key:?}", self.what)), @@ -397,7 +405,7 @@ impl<'a> Fields<'a> { /// Refuses fields that were not read. pub fn finish(self) -> Result<(), WireError> { - if let Some(extra) = self.map.keys().find(|k| !self.seen.contains(k.as_str())) { + if let Some(extra) = self.map.keys().find(|k| !self.seen.contains(&k.as_str())) { return err(format!("{}: unknown field {extra:?}", self.what)); } Ok(()) @@ -738,13 +746,13 @@ pub struct EnvelopeHead<'a> { /// field order -- without copying the body into a value tree first (BUS-01: the body is the one /// large part of a message, and it used to be copied twice on the way out). Refuses anything over /// [`MAX_ENVELOPE_BYTES`]. -pub fn encode_parts( +pub fn encode_parts( head: &EnvelopeHead<'_>, - body: &Map, + body: &B, attachments: &[Attachment], ) -> Result, WireError> { #[derive(serde::Serialize)] - struct Out<'a> { + struct Out<'a, B: serde::Serialize + ?Sized> { protocol: &'static str, major: u64, minor: u64, @@ -753,7 +761,7 @@ pub fn encode_parts( reply_to: Option<&'a str>, kind: &'static str, op: &'a str, - body: &'a Map, + body: &'a B, attachments: Vec, } let out = Out { @@ -778,6 +786,65 @@ pub fn encode_parts( } +/// An envelope encoded once, before its id is known (BUS-02). A router assigns envelope ids +/// only when its scheduler selects a frame, and it used to serialize every frame twice -- once +/// to size it, once to send it -- and deep-copy its body for each. This holds the bytes encoded +/// with an empty id and where the id goes; [`Unnumbered::number`] splices the id in, which is +/// the same bytes a whole encode with that id produces. +#[derive(Clone, Debug)] +pub struct Unnumbered { + bytes: Vec, + id_at: usize, +} + +impl Unnumbered { + /// Encodes with an empty id. Refuses an envelope that would exceed [`MAX_ENVELOPE_BYTES`] + /// once given an id of up to `max_id_len` bytes. + pub fn encode( + head: &EnvelopeHead<'_>, + body: &B, + attachments: &[Attachment], + max_id_len: usize, + ) -> Result { + debug_assert!(head.id.is_empty()); + let bytes = encode_parts(head, body, attachments)?; + if bytes.len() + max_id_len > MAX_ENVELOPE_BYTES { + return err(format!( + "envelope of {} bytes exceeds {MAX_ENVELOPE_BYTES}", + bytes.len() + max_id_len + )); + } + // The id is the first `"id":` member: protocol, major and minor precede it and none of + // them can contain that text. + const KEY: &[u8] = b"\"id\":\""; + let id_at = bytes + .windows(KEY.len()) + .position(|w| w == KEY) + .map(|at| at + KEY.len()) + .ok_or_else(|| WireError("encoded envelope has no id".into()))?; + Ok(Unnumbered { bytes, id_at }) + } + + /// The encoded length without an id. + pub fn len(&self) -> usize { + self.bytes.len() + } + + pub fn is_empty(&self) -> bool { + self.bytes.is_empty() + } + + /// The final bytes with `id` (an `Id`, which needs no JSON escaping) in place. + pub fn number(self, id: &str) -> Vec { + debug_assert!(is_id(id)); + let mut out = Vec::with_capacity(self.bytes.len() + id.len()); + out.extend_from_slice(&self.bytes[..self.id_at]); + out.extend_from_slice(id.as_bytes()); + out.extend_from_slice(&self.bytes[self.id_at..]); + out + } +} + // --------------------------------------------------------------------------------------------- // Framing diff --git a/services/flysim/crates/flybus/tests/artifacts.rs b/services/flysim/crates/flybus/tests/artifacts.rs index c3937ed..8c6d9e9 100644 --- a/services/flysim/crates/flybus/tests/artifacts.rs +++ b/services/flysim/crates/flybus/tests/artifacts.rs @@ -86,11 +86,6 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) { let store = a["writeLocation"]["storeId"].clone(); let reference = json!({"storeId": store, "artifactId": a["artifactId"], "generation": "1", "byteLength": "8", "contentType": "application/octet-stream", "digest": null}); - let att = json!([{"name": "x", "ref": reference, "ownerId": a["ownerId"]}]); - let r = raw - .call_with("publish", json!({"topic": "t.x", "payload": {}}), att) - .await; - assert_eq!(code(&r), "ARTIFACT_UNSEALED"); let r = raw .call( "artifact.open", @@ -105,7 +100,20 @@ async fn unsealed_artifacts_cannot_be_used(via: Via) { ) .await; assert_eq!(code(&r), "ARTIFACT_UNSEALED"); - assert_eq!(code(&raw.seal(&a, Value::Null).await), "OK"); + // Since the 2026-10-02 amendment (bus-v1 section 12), a sending command that names its own + // writer seals it as it is admitted: the writer is then a hold, and seals no more. + let att = json!([{"name": "x", "ref": reference, "ownerId": a["ownerId"]}]); + let r = raw + .call_with("publish", json!({"topic": "t.x", "payload": {}}), att) + .await; + assert_eq!(code(&r), "OK"); + let r = raw + .call( + "artifact.open", + json!({"ref": reference, "ownerId": a["ownerId"]}), + ) + .await; + assert_eq!(code(&r), "OK", "the writer became the sender's hold"); assert_eq!( code(&raw.seal(&a, Value::Null).await), "OWNER_INVALID", diff --git a/services/flysim/crates/flybus/tests/sealing.rs b/services/flysim/crates/flybus/tests/sealing.rs new file mode 100644 index 0000000..05bb756 --- /dev/null +++ b/services/flysim/crates/flybus/tests/sealing.rs @@ -0,0 +1,146 @@ +//! Sealing sends (bus-v1 section 12, amendment 2026-10-02): a sending command that attaches its +//! sender's own writer seals it as the command is admitted, optionally recycling the staging +//! allocation as a new writer; a refused one releases every writer it named. + +mod common; + +use std::io::Write; + +use common::{Via, code, env, obj, within}; +use flybus::ServiceConfig; +use serde_json::json; + +/// A reply that seals its writers: the caller reads exactly the bytes written, the responder's +/// handle is the hold its writer became, and the recycled writer serves the next reply. +async fn a_reply_seals_and_recycles_its_writers(via: Via) { + let e = env(via).await; + let svc_client = e.client("svc").await; + let mut svc = svc_client + .register("t.echo", ServiceConfig::default()) + .await + .unwrap(); + let caller = e.client("caller").await; + let server = tokio::spawn(async move { + let mut writer = svc_client + .artifacts() + .allocate(4096, "application/x-frame") + .await + .unwrap(); + let mut held = Vec::new(); + for round in 0..3u8 { + let req = svc.next().await.unwrap(); + // Fewer bytes than the allocation: the sealed artifact is the prefix written. + let body = vec![round; 1000 + usize::from(round)]; + writer.write_all(&body).unwrap(); + assert_eq!(writer.written(), body.len() as u64); + let unsealed = writer.into_unsealed(); + let artifact = unsealed.artifact().clone(); + let out = req + .responder() + .reply_sealing(obj(json!({"round": round})), &[("frame", &artifact)], vec![unsealed], true) + .await + .unwrap(); + assert!(out.routed); + assert!(artifact.is_hold(), "the writer became the responder's hold"); + assert_eq!(out.writers.len(), 1, "the allocation comes back as a new writer"); + writer = out.writers.into_iter().next().unwrap(); + assert_eq!(writer.byte_length(), 4096); + assert_eq!(writer.written(), 0); + assert_eq!(writer.content_type(), "application/x-frame"); + held.push(artifact); + } + (held, writer) + }); + for round in 0..3u8 { + let result = within( + "sealed reply", + caller.call_and_wait("t.echo", None, "Echo", obj(json!({})), &[]), + ) + .await + .unwrap(); + let frame = result.artifact("frame").unwrap(); + let r = frame.reference(); + assert_eq!(r.byte_length, 1000 + u64::from(round)); + assert_eq!(r.content_type, "application/x-frame"); + assert_eq!(r.digest, None); + assert_eq!(frame.read_all().await.unwrap(), vec![round; 1000 + usize::from(round)]); + } + let (held, writer) = within("server", server).await.unwrap(); + // The responder's holds read the same bytes as the caller's deliveries. + for (round, artifact) in held.iter().enumerate() { + assert_eq!(artifact.read_all().await.unwrap(), vec![round as u8; 1000 + round]); + } + assert_eq!(e.files("staging"), 1, "one staging file served every reply"); + drop((held, writer)); + e.settle("collected", |s| s.artifacts == 0 && s.store_bytes == 0) + .await; + e.settle_files("sealed", 0).await; + e.settle_files("staging", 0).await; +} + +/// A sealing attachment must describe its writer, and a refused sealing send -- refused before +/// or after the seal -- releases every writer it named. +async fn a_refused_sealing_send_releases_its_writers(via: Via) { + let e = env(via).await; + let mut raw = e.raw_hello("raw").await; + assert_eq!( + code(&raw.call("topic.declare", json!({"name": "t.x", "retained": "none"})).await), + "OK" + ); + let reference = |a: &serde_json::Map, len: &str| { + json!({"storeId": a["writeLocation"]["storeId"], "artifactId": a["artifactId"], + "generation": "1", "byteLength": len, "contentType": "application/octet-stream", + "digest": null}) + }; + + // Longer than the allocation: refused, and the writer is gone. + let (a, _) = raw.allocate(8).await; + let att = json!([{"name": "x", "ref": reference(&a, "9"), "ownerId": a["ownerId"]}]); + let r = raw.call_with("publish", json!({"topic": "t.x", "payload": {}}), att).await; + assert_eq!(code(&r), "ARTIFACT_MISMATCH"); + assert_eq!(code(&raw.seal(&a, json!(null)).await), "OWNER_INVALID"); + + // Sealed, then the command is refused (no such topic): the seal goes with it. + let (a, _) = raw.allocate(8).await; + let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]); + let r = raw.call_with("publish", json!({"topic": "t.nobody", "payload": {}}), att).await; + assert_eq!(code(&r), "NO_TOPIC"); + let r = raw + .call("artifact.open", json!({"ref": reference(&a, "8"), "ownerId": a["ownerId"]})) + .await; + assert_eq!(code(&r), "OWNER_INVALID"); + + // `recycle` needs a writer to recycle, and must be a boolean. + let r = raw + .call("publish", json!({"topic": "t.x", "payload": {}, "recycle": true})) + .await; + assert_eq!(code(&r), "INVALID_ENVELOPE"); + let (a, _) = raw.allocate(8).await; + let att = json!([{"name": "x", "ref": reference(&a, "8"), "ownerId": a["ownerId"]}]); + let r = raw + .call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": 1}), att) + .await; + assert_eq!(code(&r), "INVALID_ENVELOPE"); + + // A recycling publish returns the new writer, named by attachment. + let (a, _) = raw.allocate(8).await; + let att = json!([{"name": "x", "ref": reference(&a, "5"), "ownerId": a["ownerId"]}]); + let v = raw + .call_with("publish", json!({"topic": "t.x", "payload": {}, "recycle": true}), att) + .await + .unwrap(); + let writers = v["writers"].as_array().unwrap(); + assert_eq!(writers.len(), 1); + assert_eq!(writers[0]["name"], "x"); + let next = writers[0].as_object().unwrap().clone(); + assert_ne!(next["artifactId"], a["artifactId"]); + // The recycled writer is an ordinary writer: it seals the whole allocation. + assert_eq!(code(&raw.seal(&next, json!(null)).await), "OK"); + e.settle("only the two seals remain", |s| s.sealed_artifacts == 2) + .await; +} + +both_transports!( + a_reply_seals_and_recycles_its_writers, + a_refused_sealing_send_releases_its_writers, +);