From ff73cd958f1c3d24a0d1e74e52c24f1684e79ace Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 12:25:50 -0600 Subject: [PATCH] feat(id): track per-connection world input sessions (#840) --- pkgs/id/src/world/actor.rs | 8 +++++ pkgs/id/src/world/handle.rs | 22 +++++++++++++ pkgs/id/src/world/mod.rs | 11 +++++++ pkgs/id/src/world/tests.rs | 51 ++++++++++++++++++++++++++++++ pkgs/id/src/world_session/mod.rs | 25 ++++++++++++--- pkgs/id/src/world_session/tests.rs | 8 +++++ pkgs/id/src/world_session/types.rs | 7 ++-- 7 files changed, 125 insertions(+), 7 deletions(-) diff --git a/pkgs/id/src/world/actor.rs b/pkgs/id/src/world/actor.rs index c27352dde2..fb56ad1242 100644 --- a/pkgs/id/src/world/actor.rs +++ b/pkgs/id/src/world/actor.rs @@ -100,6 +100,7 @@ pub(crate) enum WorldCommand { Input { token: JoinCapability, input: Vec, + session_id: Option, reply: oneshot::Sender>, }, Snapshot { @@ -283,6 +284,9 @@ pub(crate) struct WorldActor { /// The participant whose input is being processed. Requests the program /// makes in response are checked against that participant's scopes. pub(crate) acting: Option, + /// The connection whose input is being processed. Ephemeral actor context; + /// it is deliberately absent from `WorldEvent` and the journal. + pub(crate) acting_session: Option, } impl WorldActor { @@ -321,6 +325,7 @@ impl WorldActor { self.metrics.record_command(started.elapsed()); self.after_change().await; self.acting = None; + self.acting_session = None; } } @@ -1132,6 +1137,7 @@ impl WorldActor { WorldCommand::Input { token, input, + session_id, reply, } => { let result = match self.core.prepare_input(&token, &input) { @@ -1140,6 +1146,7 @@ impl WorldActor { )), Ok(candidate) if self.program_healthy => { self.acting = Some(candidate.participant_id); + self.acting_session = session_id; match self .program .update(&candidate) @@ -1554,6 +1561,7 @@ impl WorldActor { ticks: BTreeMap::new(), overdue_at_open, acting: None, + acting_session: None, auth: crate::directory_auth::DirectoryAuth::default(), metrics: WorldMetrics::default(), } diff --git a/pkgs/id/src/world/handle.rs b/pkgs/id/src/world/handle.rs index ed33d591c5..f3f69ac929 100644 --- a/pkgs/id/src/world/handle.rs +++ b/pkgs/id/src/world/handle.rs @@ -87,6 +87,7 @@ impl WorldHandle { ticks: BTreeMap::new(), overdue_at_open, acting: None, + acting_session: None, auth: crate::directory_auth::DirectoryAuth::default(), }; tokio::spawn(actor.run(receiver)); @@ -607,11 +608,32 @@ impl WorldHandle { /// Submit bounded opaque game input. pub async fn input(&self, token: JoinCapability, input: Vec) -> Result { + self.input_with_session(token, input, None).await + } + + /// Submit bounded opaque game input from a live session connection. + pub(crate) async fn input_from_session( + &self, + token: JoinCapability, + input: Vec, + session_id: SessionId, + ) -> Result { + self.input_with_session(token, input, Some(session_id)) + .await + } + + async fn input_with_session( + &self, + token: JoinCapability, + input: Vec, + session_id: Option, + ) -> Result { let (reply, response) = oneshot::channel(); self.commands .send(WorldCommand::Input { token, input, + session_id, reply, }) .await diff --git a/pkgs/id/src/world/mod.rs b/pkgs/id/src/world/mod.rs index d4149a1a4d..0117d3ffd1 100644 --- a/pkgs/id/src/world/mod.rs +++ b/pkgs/id/src/world/mod.rs @@ -50,6 +50,17 @@ pub(crate) use util::{ constant_time_eq, hex_decode_32, sanitize_chat, sanitize_display_name, token_digest, }; +/// Identity of one live connection. It stays in memory only and is never part +/// of a world event or journal entry. +#[derive(Clone, Copy, Eq, Hash, PartialEq)] +pub(crate) struct SessionId(u64); + +impl SessionId { + pub(crate) const fn new(value: u64) -> Self { + Self(value) + } +} + /// A chat participant may send at most this many lines during the rolling window. pub(crate) const CHAT_RATE_BURST: u8 = 50; pub(crate) const CHAT_RATE_WINDOW: std::time::Duration = std::time::Duration::from_secs(10); diff --git a/pkgs/id/src/world/tests.rs b/pkgs/id/src/world/tests.rs index f06e5a3d33..7ffe00a5b7 100644 --- a/pkgs/id/src/world/tests.rs +++ b/pkgs/id/src/world/tests.rs @@ -3482,6 +3482,7 @@ mod schedule_tests { .handle(WorldCommand::Input { token: token.clone(), input: document.to_string().into_bytes(), + session_id: None, reply, }) .await; @@ -3490,6 +3491,56 @@ mod schedule_tests { let _ = response.await.unwrap().unwrap(); } + #[tokio::test] + async fn input_session_attribution_is_ephemeral_and_distinguishes_connections() { + let (mut actor, _, token, journal) = scheduling_actor("sessions", &[], false); + const SESSION_A: u64 = 0x5eed_cafe_0000_0001; + const SESSION_B: u64 = 0x5eed_cafe_0000_0002; + let session_ids = [SessionId::new(SESSION_A), SessionId::new(SESSION_B)]; + let mut participant = None; + + for session_id in session_ids { + let (reply, response) = tokio::sync::oneshot::channel(); + actor + .handle(WorldCommand::Input { + token: token.clone(), + input: b"{}".to_vec(), + session_id: Some(session_id), + reply, + }) + .await; + + let acting = actor + .acting + .expect("input participant is set while processing"); + if let Some(first) = participant { + assert_eq!(acting, first); + } else { + participant = Some(acting); + } + assert!(actor.acting_session == Some(session_id)); + response.await.unwrap().unwrap(); + actor.after_change().await; + actor.acting = None; + actor.acting_session = None; + } + + let committed: Vec<_> = journal + .entries() + .into_iter() + .filter(|entry| matches!(entry, JournalEntry::Committed { .. })) + .collect(); + assert_eq!(committed.len(), 2); + for entry in committed { + let value = serde_json::to_value(entry).unwrap(); + assert_eq!(value.as_object().unwrap().len(), 2); + assert!(value.get("session_id").is_none()); + let serialized = value.to_string(); + assert!(!serialized.contains(&SESSION_A.to_string())); + assert!(!serialized.contains(&SESSION_B.to_string())); + } + } + /// The records the program last published. fn records(actor: &WorldActor) -> Arc { actor.records_sender.borrow().1.clone() diff --git a/pkgs/id/src/world_session/mod.rs b/pkgs/id/src/world_session/mod.rs index 2e00f24660..0c86aa8129 100644 --- a/pkgs/id/src/world_session/mod.rs +++ b/pkgs/id/src/world_session/mod.rs @@ -15,6 +15,7 @@ //! is (an Iroh node ID); that never grants world authority. use std::sync::Arc; +use std::sync::atomic::Ordering; use std::time::Duration; use anyhow::Context as _; @@ -30,8 +31,8 @@ use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore, broadcast}; use crate::directory_auth::Signed; use crate::time::unix_ms; use crate::world::{ - Authority, CapabilityBounds, FileScope, Isolation, JoinCapability, Participant, WorldHandle, - WorldMetrics, WorldPolicy, WorldScopes, + Authority, CapabilityBounds, FileScope, Isolation, JoinCapability, Participant, SessionId, + WorldHandle, WorldMetrics, WorldPolicy, WorldScopes, }; use crate::world_compile::Compiler; #[cfg(feature = "sandbox")] @@ -61,6 +62,11 @@ pub use types::{ }; impl WorldService { + /// Allocate an ephemeral identity for one accepted connection. + pub(crate) fn next_session_id(&self) -> SessionId { + SessionId::new(self.next_session_id.fetch_add(1, Ordering::Relaxed)) + } + /// Accept native (ELF) module installs. Wasm stays the default tier. #[must_use] pub const fn with_native_enabled(mut self) -> Self { @@ -181,6 +187,7 @@ impl WorldService { mail: None, outbox: None, profile_operation: Arc::new(Mutex::new(())), + next_session_id: Arc::new(std::sync::atomic::AtomicU64::new(1)), } } @@ -1850,6 +1857,7 @@ async fn joined( after: Option, ) { let world = service.world(); + let session_id = service.next_session_id(); // Subscribe before taking the snapshot so no event can fall in the gap; // events at or below the cursor are skipped when delivered. let mut events = world.subscribe(); @@ -1935,7 +1943,7 @@ async fn joined( tokio::select! { inbound = io.recv() => match inbound { Inbound::Text(text) => { - if !handle_client_frame(service, io, &token, &text, &mut viewport, cursor).await { + if !handle_client_frame(service, io, &token, &text, &mut viewport, cursor, session_id).await { break; } } @@ -2134,6 +2142,7 @@ async fn handle_client_frame( text: &str, viewport: &mut Option, sequence: u64, + session_id: SessionId, ) -> bool { let world = service.world(); let Ok(value) = serde_json::from_str::(text) else { @@ -2207,10 +2216,16 @@ async fn handle_client_frame( ) .await; }; - world.input(token.clone(), bytes).await + world + .input_from_session(token.clone(), bytes, session_id) + .await } ClientFrame::Input { data_hex } => match decode_hex(&data_hex) { - Some(data) => world.input(token.clone(), data).await, + Some(data) => { + world + .input_from_session(token.clone(), data, session_id) + .await + } None => { return send_error(service.frame_meter(), io, "input data must be hexadecimal") .await; diff --git a/pkgs/id/src/world_session/tests.rs b/pkgs/id/src/world_session/tests.rs index 7a8968ffb4..546d12ceca 100644 --- a/pkgs/id/src/world_session/tests.rs +++ b/pkgs/id/src/world_session/tests.rs @@ -121,6 +121,14 @@ mod tests { ) } + #[tokio::test] + async fn cloned_service_allocates_distinct_ids_for_connections() { + let service = service(None); + let another_connection = service.clone(); + + assert!(service.next_session_id() != another_connection.next_session_id()); + } + #[tokio::test] async fn execution_profile_change_is_admin_only_and_does_not_replace_live_program() { struct MarkerProgram; diff --git a/pkgs/id/src/world_session/types.rs b/pkgs/id/src/world_session/types.rs index fbc0bf27e2..25161b7a5a 100644 --- a/pkgs/id/src/world_session/types.rs +++ b/pkgs/id/src/world_session/types.rs @@ -1,5 +1,6 @@ use std::collections::BTreeMap; use std::sync::Arc; +use std::sync::atomic::AtomicU64; use std::time::Duration; use iroh_blobs::api::{Store, TempTag}; @@ -8,8 +9,8 @@ use tokio::sync::{Mutex, RwLock, Semaphore}; use crate::directory_auth::Signed; use crate::world::{ - CapabilityBounds, FileScope, Isolation, MetricsSnapshot, WorldEvent, WorldHandle, WorldMetrics, - WorldPolicy, WorldSnapshot, + CapabilityBounds, FileScope, Isolation, MetricsSnapshot, SessionId, WorldEvent, WorldHandle, + WorldMetrics, WorldPolicy, WorldSnapshot, }; use crate::world_compile::Compiler; use crate::world_hub::WorldInfo; @@ -497,6 +498,8 @@ pub struct WorldService { /// The world's host metrics registry (F11.7), shared with the actor: /// the session layer records the frame bytes it sends into it. pub(crate) metrics: WorldMetrics, + /// Monotonic, process-local IDs for live connections to this service. + pub(crate) next_session_id: Arc, } impl std::fmt::Debug for WorldService {